<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Home\Controller;

use Qiniu\Auth;
use Think\Exception;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
header('Access-Control-Allow-Origin: *');
class ApisController extends HomeController
{
	/**
	 * 系统非常规MD5加密方法
	 * @param        string        $str        要加密的字符串
	 * @return       string
	 */
	public function think_ucenter_md5($str, $key = 'ThinkUCenter')
	{
		return '' === $str ? '' : md5(sha1($str) . $key);
	}

	/**
	 * 解密用户信息并注册登录
	 * */
	public function getWxUserInfo()
	{
		$input = I('post.');
		$code = $input['code'];
		$encryptedData = $input['encryptedData'];
		$iv = $input['iv'];
		$iid = $input['iid'] ? $input['iid'] : C('ADMIN_INSTITUTION_ID');

		if (empty($code)) return api_return(2, 'code不能为空');
		if (empty($encryptedData)) return api_return(2, 'encryptedData不能为空');
		if (empty($iv)) return api_return(2, 'iv不能为空');
		if (empty($iid)) api_return(2, '平台机构ID缺失，登录失败');

		$appid = C('XCX_APPID');
		$secret = C('XCX_APPSECRET');
		$grant_type = 'authorization_code';
		$url = 'https://api.weixin.qq.com/sns/jscode2session?';
		$param = array(
			'appid' => $appid,
			'secret' => $secret,
			'js_code' => $code,
			'grant_type' => $grant_type
		);
		$param_str = http_build_query($param);
		$url .= $param_str;
		$user_data = json_decode(file_get_contents($url));
		$openid = $user_data->openid;
		$session_key = $user_data->session_key;

		$data = "";
		vendor('wxApp.wxBizDataCrypt');//引入微信解密文件
		$wxBizDataCrypt = new \WXBizDataCrypt($appid, $session_key);
		$errCode = $wxBizDataCrypt->decryptData($encryptedData, $iv, $data);
		if ($errCode == 0) {
			$userinfo = json_decode($data, true);
			//登录成功返回用户信息；自定义
			$info = M('ucenter_member')->field('id,avatar,username,id_account,sex,iid')->where(array('openid' => $openid))->find();
			if ($info) {
				M('ucenter_member')->where(array('openid' => $userinfo['openId']))->setInc('login_count');

				return api_return(1, '登录成功', $info);
			} else {
				//注册用户业务逻辑处理
				//注册用户信息；自定义
				$ucenter_register_info = array(
					'iid' => $iid,
					'avatar' => $userinfo['avatarUrl'],
					'username' => $userinfo['nickName'],
					'sex' => $userinfo['gender'],
					'openid' => $openid,
					'user_type' => 2,
					'password' => $this->think_ucenter_md5(C('DEFAULT_PWD'), '{`47CxmWwv[nV/?)^L1YRz-&0%rjQAtXp53.,#qT'),
					'id_account' => getRandIdAccount()
				);
				$res = M('ucenter_member')->add($ucenter_register_info);
				if ($res) {
					$member_register_info = array(
						'uid' => $res,
						'nickname' => $userinfo['nickName'],
						'sex' => $userinfo['gender'],
					);
					M('member')->add($member_register_info);
					//需要获取的用户信息；自定义
					$user_info = getUserInfo($res, 'id,avatar,username,id_account,sex,iid');

					M('ucenter_member')->where(array('openid' => $userinfo['openid']))->setInc('login_count');

					return api_return(1, '登录成功', $user_info);
				} else {
					return api_return(2, '用户信息注册失败');
				}
			}
		} else {
			return api_return(2, '登录失败，请稍后重试，错误码：' . $errCode);
		}
	}


	/**
	 * 解密用户信息并注册登录
	 * */
	public function getWxUserInfo_bak()
	{
		$input = I('post.');
		$session_key = $input['session_key'];
		$openid = $input['openid'];
		$encryptedData = $input['encryptedData'];
		$iv = $input['iv'];
		$iid = $input['iid'] ? $input['iid'] : C('ADMIN_INSTITUTION_ID');

		if (empty($session_key)) return api_return(2, '参数缺失');
		if (empty($openid)) return api_return(2, 'openid缺失');
		if (empty($encryptedData)) return api_return(2, 'encryptedData不能为空');
		if (empty($iv)) return api_return(2, 'iv不能为空');
		if (empty($iid)) api_return(2, '平台机构ID缺失，登录失败');

		$appid = C('XCX_APPID');
		$data = "";
		vendor('wxApp.wxBizDataCrypt');//引入微信解密文件
		$wxBizDataCrypt = new \WXBizDataCrypt($appid, $session_key);
		$errCode = $wxBizDataCrypt->decryptData($encryptedData, $iv, $data);
		if ($errCode == 0) {
			$userinfo = json_decode($data, true);
			//登录成功返回用户信息；自定义
			$info = M('ucenter_member')->field('id,avatar,username,id_account,sex,iid')->where(array('openid' => $openid))->find();
			if ($info) {
				M('ucenter_member')->where(array('openid' => $userinfo['openId']))->setInc('login_count');

				return api_return(1, '登录成功', $info);
			} else {
				//注册用户业务逻辑处理
				//注册用户信息；自定义
				$ucenter_register_info = array(
					'iid' => $iid,
					'avatar' => $userinfo['avatarUrl'],
					'username' => $userinfo['nickName'],
					'sex' => $userinfo['gender'],
					'openid' => $userinfo['openId'],
					'user_type' => 2,
					'password' => $this->think_ucenter_md5(C('DEFAULT_PWD'), '{`47CxmWwv[nV/?)^L1YRz-&0%rjQAtXp53.,#qT'),
					'id_account' => getRandIdAccount()
				);
				$res = M('ucenter_member')->add($ucenter_register_info);
				if ($res) {
					$member_register_info = array(
						'uid' => $res,
						'nickname' => $userinfo['nickName'],
						'sex' => $userinfo['gender'],
					);
					M('member')->add($member_register_info);
					//需要获取的用户信息；自定义
					$user_info = getUserInfo($res, 'id,avatar,username,id_account,sex,iid');

					M('ucenter_member')->where(array('openid' => $userinfo['openId']))->setInc('login_count');

					return api_return(1, '登录成功', $user_info);
				} else {
					return api_return(2, '用户信息注册失败');
				}
			}
		} else {
			return api_return(2, '登录失败，请稍后重试，错误码：' . $errCode);
		}
	}

	/**
	 * 绑定手机号
	 * */
	public function bindMobile()
	{
		$input = I('post.');
		$uid = $input['uid'];
		$mobile = $input['mobile'];
		$code = $input['code'];
		if (empty($uid)) return api_return(2, '用户id缺失');
		if (empty($mobile)) return api_return(2, '请传入手机号');
		if (empty($code)) return api_return(2, '请传入验证码');
		$count = M('ucenter_member')->where(['mobile' => $mobile])->count();
		if ($count > 0) return api_return(2, '该手机号已被使用');
		$sms = M('sms_code')->where(['mobile' => $mobile])->order('create_time desc')->limit(1)->find();
		if (!$sms) return api_return(2, '该手机号码未发送验证码');
		if ($sms['failure_time'] < time()) return api_return(2, '验证码已失效');
		if ($code != $sms['code']) return api_return(2, '验证码错误');
		$res = M('ucenter_member')->where(['id' => $uid])->setField('mobile', $mobile);
		if ($res) {
			return api_return(1, '绑定手机号成功');
		} else {
			return api_return(2, '绑定手机号失败');
		}
	}

	/**
	 * 首页
	 * */
	public function index()
	{
		$input = I('post.');
		$iid = $input['iid'];//机构id
		$uid = $input['uid'];

		if (empty($iid)) api_return(2, '请先绑定机构');

		//机构信息
		$institution_info = M('institution')->field('id,name,banner')->where(array('id' => $iid))->find();

		$picture_gallery_list = M('picture_gallery')->field('img')->where(" style = 1 OR (style = 2 && (show_start_time <= " . time() . " AND show_end_time >= " . time() . ") ) ")->select();
		$picture_imgs = $picture_gallery_list ? implode(',', array_column($picture_gallery_list, 'img')) : '';
		$institution_info['banner'] = doImgs(($institution_info['banner'] ? $institution_info['banner'] : '') . ($picture_imgs ? ',' . $picture_imgs : ''));

		//直播课列表
		$live_where['iid'] = $iid;
		$live_where['audit_status'] = 1;
		$live_where['status'] = 1;
		$live_where['is_del'] = 0;
		$live_where['is_activity'] = 0;
		$live_where['live_time'] = array('egt', time());
		$live_list = M('live_course')->field('id,name,img,price,live_time,teacher_id')->where($live_where)->order('id desc')->limit(5)->select();
		if ($live_list) {
			foreach ($live_list as &$v) {
				$v['img'] = getPicture($v['img']);
				$v['live_time'] = time_format($v['live_time'], 'H:i');

				//查询老师信息
				$teacher_info = M('teacher')->field('id,name,avatar_id,tag')->where(array('id' => $v['teacher_id']))->find();
				$v['teacher_name'] = $teacher_info['name'];
				$v['teacher_avatar'] = doAvatar($teacher_info['avatar_id']);
				$v['teacher_tag'] = $teacher_info['tag'];

				//查询是否报名；大于0则表示已报名
				if ($uid) {
					$is_enlist = M('order o')->join('teach_vice_order vo ON o.id = vo.order_id')->where(array('o.uid' => $uid, 'o.type' => 1, 'o.is_pay' => 1, 'vo.to_id' => $v['id']))->count();
				} else {
					$is_enlist = 0;
				}
				$v['is_enlist'] = $is_enlist;
			}
		}

		//在线课列表
		$where['iid'] = $iid;
		$where['is_activity'] = 0;
		$where['is_upper'] = 1;
		$where['is_del'] = 0;
		$video_list = M('video_course')->field('id,img,name,price,sales_count')->where($where)->limit(4)->order('id desc')->select();
		if ($video_list) {
			foreach ($video_list as &$v) {
				$v['img'] = getPicture($v['img']);
				$v['video_tree_count'] = videoTreeCount($v['id']);
			}
		} else {
			$video_list = array();
		}

		//面授课列表
		$face_list = M('face_course')->field('id,img,name,end_enlist_time,price')->where(array('iid' => $iid, 'is_upper' => 1, 'is_activity' => 0, 'is_del' => 0, 'end_enlist_time' => array('gt', time())))->order('id desc')->limit(4)->select();
		if ($face_list) {
			foreach ($face_list as &$v) {
				$v['img'] = getPicture($v['img']);
				$v['end_enlist_time'] = time_format($v['end_enlist_time'], 'm.d') . '截止报名';
			}
		} else {
			$face_list = array();
		}

		//书籍推荐
		$goods_list = M('goods')->field('id,imgs,min_price,name')->where(array('is_recommend' => 1, 'is_del' => 0))->order('id desc')->limit(5)->select();
		if ($goods_list) {
			foreach ($goods_list as &$v) {
				$imgs = doImgs($v['imgs']);
				$v['img'] = $imgs[0]['path'];
			}
		} else {
			$goods_list = array();
		}

		//限时秒杀
//		$end_time = strtotime(date('Y-m-d') . '+2 day') - 1;
		$skill_list = M('seckill')
			->field("id,course_id,category,name,price,status,FROM_UNIXTIME(start_time,'%Y-%m-%d %H:%i') real_time,FROM_UNIXTIME(start_time,'%Y-%m-%d') day,FROM_UNIXTIME(start_time,'%H:%i') time")
			->where(array('iid' => $iid, 'status' => array('neq', 2), 'end_time' => array('gt', time()), 'count' => array('gt', 0)))
			->select();

		if ($skill_list) {
			foreach ($skill_list as &$v) {
				if ($v['category'] == 1) {
					//面授课
					$db = M('face_course');
					$field = 'img,price,enlist_count sales_count,count';
				} else if ($v['category'] == 2) {
					//点播课
					$db = M('video_course');
					$field = 'img,price,sales_count';
				} else {
					//直播课
					$db = M('live_course');
					$field = 'img,price,enlist_count sales_count';
				}

				$skill_course_info = $db->field($field)->where(array('id' => $v['course_id']))->find();
				$v['img'] = getPicture($skill_course_info['img']);
				$v['old_price'] = $skill_course_info['price'];
				$v['sales_count'] = $skill_course_info['sales_count'];
				if ($v['category'] == 2) {
					$v['count'] = videoTreeCount($v['course_id']);
				} else {
					$v['count'] = $skill_course_info['count'] ? $skill_course_info['count'] : 0;
				}

				$skill_time_list = array_column($skill_list, 'real_time');
				if ($skill_time_list) {
					foreach ($skill_time_list as $key => &$val) {
						$val = explode(' ', $val);
						if (date('Y-m-d') == $val[0]) {
							if ($val[0] . ' ' . $val[1] <= date('Y-m-d H:i')) {
								$val[2] = '立即秒杀';
							} else {
								$val[2] = '今日开抢';
							}
						} else if (date('Y-m-d') > $val[0]) {
							$val[2] = '立即秒杀';
						} else {
							$day = diffBetweenTwoDays(date('Y-m-d'), $val[0]);
							if ($day == 1) {
								$val[2] = '明日开抢';
							} else if ($day > 1) {
								$val[2] = $day . '天后开抢';
							}
						}
					}
				}
			}
		} else {
			$skill_list = array();
			$skill_time_list = array();
		}
		$skill_info = array(
			'skill_list' => $skill_list,
			'skill_time_list' => array_merge(array_unique($skill_time_list, SORT_REGULAR))
		);

		//拼团推荐
		$group_where['iid'] = $iid;
		$group_where['status'] = 1;
		$group_where['start_time'] = array('lt', time());
		$group_where['end_time'] = array('egt', time());
		$group_list = M('group_work')->field('id,category,course_id,group_price,chief_price')->where($group_where)->order('id desc')->limit(4)->select();
		if ($group_list) {
			foreach ($group_list as &$v) {
				//拼团人数
				$people_count = M('group_join')->where(array('gid' => $v['id'], 'status' => array('IN', '1,2')))->count();
				$v['people_count'] = $people_count;

				$people_list = M('group_join g')->join('teach_ucenter_member u ON g.uid = u.id')->field('u.id,u.avatar')->where(array('g.gid' => $v['id'], 'g.status' => array('IN', '1,2')))->order('g.id desc')->limit(3)->select();
				if ($people_list) {
					foreach ($people_list as &$val) {
						$val['avatar'] = doAvatar($val['avatar']);
					}
				} else {
					$people_list = array();
				}
				$v['people_list'] = $people_list;

				if ($v['category'] == 1) {
					//面授课
					$course_info = M('face_course')->field('id,img,name')->where(array('id' => $v['course_id']))->find();
				} else if ($v['category'] == 2) {
					//在线课
					$course_info = M('video_course')->field('id,img,name')->where(array('id' => $v['course_id']))->find();
				} else if ($v['category'] == 3) {
					//直播课
					$course_info = M('live_course')->field('id,img,name')->where(array('id' => $v['course_id']))->find();
				}
				$v['img'] = getPicture($course_info['img']);
				$v['name'] = $course_info['name'];
			}
		} else {
			$group_list = array();
		}

		//师资团队所属版块
		$empty_section_teacher = array(
			array(
				'id' => 0,
				'name' => '全部'
			)
		);
		$section_teacher_list = M('section_teacher')->field('id,name')->where(array('iid' => $iid))->order('id asc')->select();
		if ($section_teacher_list) {
			$section_teacher_list = array_merge($empty_section_teacher, $section_teacher_list);
		} else {
			$section_teacher_list = $empty_section_teacher;
		}

		//师资团队
		$teacher_list = M('teacher')->field('id,name,avatar_id,tag,desc,sign')->where(array('iid' => $iid, 'is_del' => 0))->order('id desc')->select();
		if ($teacher_list) {
			foreach ($teacher_list as &$v) {
				$v['avatar'] = getPicture($v['avatar_id']);
			}
		} else {
			$teacher_list = array();
		}

		//最新资讯
		$information_list = M('information')->field('id,img,title,create_time')->order('id desc')->limit(3)->select();
		if ($information_list) {
			foreach ($information_list as &$v) {
				$v['img'] = getPicture($v['img']);
				$v['create_time'] = time_format($v['create_time'], 'y-d');
			}
		}

		$data = array(
			'institution_info' => $institution_info,
			'live_list' => $live_list,
			'video_list' => $video_list,
			'face_list' => $face_list,
			'goods_list' => $goods_list,
			'section_teacher_list' => $section_teacher_list,
			'section_teacher_index' => 0,
			'skill_info' => $skill_info,
			'group_list' => $group_list,
			'teacher_list' => $teacher_list,
			'information_list' => $information_list
		);
		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 首页搜索列表
	 * */
	public function indexSearch()
	{
		$input = I('post.');

		$iid = $input['iid'];
		$search_value = $input['search_value'];
		$type = $input['type'];//1：在线课，2：题库，3：直播课，4：面授课，5：商城
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		switch ($type) {
			case 1:
				$model = M('video_course');
				$where['is_activity'] = 0;
				$where['iid'] = $iid;
				$order = 'id desc';
				break;
			case 2:
				$model = M('practice');
				$order = 'sort asc';
				break;
			case 3:
				$model = M('live_course');
				$order = 'id desc';
				$where['iid'] = $iid;
				$where['is_activity'] = 0;
				break;
			case 4:
				$model = M('face_course');
				$where['iid'] = $iid;
				$where['is_activity'] = 0;
				$order = 'id desc';
				break;
			case 5:
				$model = M('goods');
				break;
		}
		if ($search_value) $where['name'] = array('LIKE', '%' . $search_value . '%');

		$list = $model->where($where)->order($order)->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);

				$v['tags'] = $v['tags'] ? explode(',', $v['tags']) : array();
				$v['single_count'] = intval($v['single_count']);
				$v['check_count'] = intval($v['check_count']);

				//查询老师信息
				if ($type == 3) {
					$teacher_info = M('teacher')->field('id,name,avatar_id,tag')->where(array('id' => $v['teacher_id']))->find();
					$v['teacher_name'] = $teacher_info['name'];
					$v['teacher_avatar'] = doAvatar($teacher_info['avatar_id']);
					$v['teacher_tag'] = $teacher_info['tag'];
					$v['live_time'] = time_format($v['live_time'], 'H:i');
				} else if ($type == 5) {
					$imgs = doImgs($v['imgs']);
					$v['img'] = $imgs[0]['path'];
				}
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 所属版块师资团队列表数据
	 * */
	public function sceenTeacherList()
	{
		$input = I('post.');

		$iid = $input['iid'];
		$section_id = $input['section_id'];//所属版块id

		if (empty($iid)) api_return(2, '请先绑定机构');

		$where = ' iid = ' . $iid . ' and is_del = 0 ';
		if ($section_id > 0) $where .= ' and FIND_IN_SET(' . $section_id . ', section_ids) ';

		$teacher_list = M('teacher')->field('id,name,avatar_id,tag,desc,sign')->where($where)->order('id desc')->select();

		if ($teacher_list) {
			foreach ($teacher_list as &$v) {
				$v['avatar'] = getPicture($v['avatar_id']);
			}
		} else {
			$teacher_list = array();
		}

		api_return(1, '获取数据成功', $teacher_list);
	}

	/**
	 * 在线课列表
	 * */
	public function videoList()
	{
		$input = I('post.');

		$iid = $input['iid'];//机构id
		$name = $input['name'];
		$one_type_id = $input['one_type_id'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($iid)) api_return(2, '请先绑定机构');

		$empty_list = array(
			array(
				'id' => 0,
				'name' => '全部',
				'active' => 1
			)
		);
		$type_list = M('video_course_type')->field('id,name')->where(array('pid' => 0))->select();
		if ($type_list) {
			foreach ($type_list as &$v) {
				$v['active'] = 0;
			}
		} else {
			$type_list = array();
		}
		$type_list = array_merge($empty_list, $type_list);

		$where['iid'] = $iid;
		$where['is_activity'] = 0;
		$where['is_upper'] = 1;
		$where['is_del'] = 0;
		if ($one_type_id) $where['one_type_id'] = $one_type_id;
		if ($name) $where['name'] = array('LIKE', '%' . $name . '%');
		$list = M('video_course')->field('id,img,name,price,is_activity')->where($where)->page($page, $pagesize)->order('id desc')->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);
				$v['video_tree_count'] = videoTreeCount($v['id']);
			}
		} else {
			$list = array();
		}
		$data = array(
			'type_list' => $type_list,
			'list' => $list
		);
		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 在线课详情
	 * 严格控制用户之前购买视频课程没过期的情况下不能再次购买
	 * */
	public function videoDetail()
	{
		$input = I('post.');

		$id = $input['id'];
		$iid = $input['iid'];
		$uid = $input['uid'];
		$share_uid = $input['share_uid'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($id)) api_return(2, '课程ID缺失');
		if (empty($iid)) api_return(2, '机构ID缺失');

		$info = M('video_course')->field('id,name,img,imgs,price,desc,is_activity,copy_id')->where(array('id' => $id, 'iid' => $iid, 'is_del' => 0))->find();
		if ($info) {
			$info['img'] = getPicture($info['img']);
			$info['imgs'] = doImgs($info['imgs']);

			$info['desc'] = str_replace('<img src="', '<img style="width: 100%; height: auto" src="' . getHost(), $info['desc']);

			//查询活动时间
			if ($info['is_activity'] > 0) {
				$activity_time = getCourseActivityTime($info['id'], 2, $info['is_activity']);
			} else {
				$activity_time = array(
					'start_time' => 0,
					'end_time' => 9999999999
				);
			}
			$info['activity_time'] = $activity_time;

			//获取活动数据
			$activity_course_info = getActivityCourseInfo($id, 2, $info['price'], $info['is_activity']);
			$info['group_len'] = count($activity_course_info['group_list']);
			$info['group_list'] = $activity_course_info['group_list'];
			$info['all_group_people'] = $activity_course_info['all_group_people'];
			$info['price'] = $activity_course_info['price'];

			//查询课程是否收藏
			$is_collect = 0;
			if ($uid > 0) $is_collect = M('collect')->where(array('uid' => $uid, 'to_id' => $id, 'type' => 1))->getField('is_collect');
			$info['is_collect'] = $is_collect ? $is_collect : 0;

			$user_video_course_info = M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $id))->find();
			//课程目录
			$video_tree = M('video_tree')->field('id,name')->where(array('vc_id' => $info['copy_id'], 'pid' => 0))->order('id asc')->select();
			if ($video_tree) {
				foreach ($video_tree as &$v) {
					$video_tree_son = M('video_tree')->field('id,name,is_look,duration')->where(array('vc_id' => $info['copy_id'], 'pid' => $v['id']))->order('id asc')->select();
					if ($video_tree_son) {
						foreach ($video_tree_son as &$val) {
							$val['duration'] = durationFormat($val['duration']);
							if ($user_video_course_info['look_auth'] == 1) $val['is_look'] = 2;
						}
					}
					$v['video_tree_son'] = $video_tree_son ? $video_tree_son : array();
				}
			} else {
				$video_tree = array();
			}
			$info['video_tree'] = $video_tree;

			//评价列表
			$comment_list = M('comment')->field('id,uid,star,content,create_time')->where(array('to_id' => $id, 'status' => 1))->order('id desc')->page($page, $pagesize)->select();
			if ($comment_list) {
				foreach ($comment_list as &$v) {
					$user_info = M('ucenter_member')->field('username,avatar')->where(array('id' => $v['uid']))->find();
					$v['username'] = $user_info['username'] ? $user_info['username'] : '';
					$v['avatar'] = doAvatar($user_info['avatar']);

					$v['star'] = intval($v['star']);
					$v['star_num'] = $v['star'] . '.0';

					$v['create_time'] = time_format($v['create_time'], 'm/d H:i');
				}
			} else {
				$comment_list = array();
			}
			$info['comment_list'] = $comment_list;

			//评价数量
			$comment_count = M('comment')->where(array('to_id' => $id, 'type' => 1, 'status' => 1))->count();
			$info['comment_count'] = $comment_count ? $comment_count : 0;

			//评星总数
			$star = M('comment')->where(array('to_id' => $id, 'type' => 1, 'status' => 1))->sum('star');

			if ($comment_count > 0) {
				$agv_star_num = $star / $comment_count;
				$agv_star = intval($agv_star_num);
				$info['agv_star_num'] = sprintf("%.1f", $agv_star_num);
				$info['agv_star'] = $agv_star;
			} else {
				$info['agv_star_num'] = '5.0';
				$info['agv_star'] = 5;
			}

			//按钮控制；1：立即购买，2：发起拼团，3：参与拼团，4：立即秒杀，5：不显示按钮
			$user_video_count = M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $id))->where(' expire_time > ' . time() . ' || expire_time = 0 ')->count();
			if ($user_video_count > 0) {
				//严格控制用户之前购买视频课程没过期的情况下不能再次购买
				$info['btn'] = 5;
				$info['btn_name'] = '';
			} else {
				if ($info['is_activity'] == 0) {
					//无活动
					$info['btn'] = 1;
					$info['btn_name'] = '立即购买';
				} else if ($info['is_activity'] == 1) {
					//团购活动
					$work_info = M('group_work')->where(array('course_id' => $id, 'category' => 2, 'status' => 1))->find();
					if ($work_info) {
						$info['group_price'] = $work_info['group_price'];
						$info['chief_price'] = $work_info['chief_price'];

						//团ID，供底部参与拼团按钮使用
						$chief_group_join_info = M('group_join')->where(array('uid' => $share_uid, 'gid' => $work_info['id']))->find();
						$group_join_pid = $chief_group_join_info['is_chief'] == 1 ? $chief_group_join_info['id'] : $chief_group_join_info['pid'];
						$info['group_join_pid'] = $group_join_pid ? $group_join_pid : 0;

						//隐藏底部【参与拼团】按钮，原因，用户分享的这个团人数满了
						if ($chief_group_join_info['status'] == 2) $info['hide_btn'] = true;
					}

					$join_count = M('group_join')->where(array('gid' => $work_info['id'], 'uid' => $uid, 'status' => array('IN', '1,2')))->count();
					if ($join_count == 0) {
						//团个数
						$chief_count = M('group_join')->where(array('gid' => $work_info['id'], 'pid' => 0, 'status' => array('IN', '1,2')))->count();
						if ($chief_count >= $work_info['group_limit_number'] && $chief_count > 0) {
							$info['btn'] = 3;
							$info['btn_name'] = '参与拼团';
						} else {
							if ($share_uid > 0) {
								//查询分享者是否在团中
								$share_join_count = M('group_join')->where(array('gid' => $work_info['id'], 'uid' => $share_uid, 'status' => array('IN', '1,2')))->count();
								if ($share_join_count > 0) {
									$info['btn'] = 3;
									$info['btn_name'] = '参与拼团';
								} else {
									$info['btn'] = 2;
									$info['btn_name'] = '发起拼团';
								}
							} else {
								$info['btn'] = 2;
								$info['btn_name'] = '发起拼团';
							}
						}
					} else {
						$info['btn'] = 5;
						$info['btn_name'] = '';
					}
				} else {
					//秒杀活动
					$user_video_course_info = M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $id))->find();
					if ($user_video_course_info) {
						if ($user_video_course_info['expire_time'] == 0 || $user_video_course_info['expire_time'] > time()) {
							$info['btn'] = 5;
							$info['btn_name'] = '';
						} else {
							//秒杀活动
							$info['btn'] = 4;
							$info['btn_name'] = '立即秒杀';
						}
					} else {
						//秒杀活动
						$info['btn'] = 4;
						$info['btn_name'] = '立即秒杀';
					}
				}
			}

			$video_book_list = M('video_book')->field('id,goods_id,img,name,price,sales_count')->where(array('video_id' => $id))->select();
			if ($video_book_list) {
				foreach ($video_book_list as &$v) {
					$v['img'] = getPicture($v['img']);
					$v['check'] = false;
				}
			}
			$info['video_book_list'] = $video_book_list ? $video_book_list : array();

			$mobile = getDbFieldValue('institution', array('id' => $iid), 'mobile');
			$info['mobile'] = $mobile;

			//多少人学过
			$study_list = M('video_study')->where(array('vc_id' => $id))->group('uid')->select();
			$info['study_count'] = count($study_list);

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '课程不存在或已删除');
		}
	}

	/**
	 * 加载在线课程评价列表
	 * */
	public function loadVideoCourseComment()
	{
		$input = I('post.');

		$id = $input['id'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($id)) api_return(2, '课程ID缺失');

		//评价列表
		$comment_list = M('comment')->field('id,uid,star,content,create_time')->where(array('to_id' => $id, 'status' => 1))->order('id desc')->page($page, $pagesize)->select();
		if ($comment_list) {
			foreach ($comment_list as &$v) {
				$user_info = M('ucenter_member')->field('username,avatar')->where(array('id' => $v['uid']))->find();
				$v['username'] = $user_info['username'] ? $user_info['username'] : '';
				$v['avatar'] = doAvatar($user_info['avatar']);

				$v['star'] = intval($v['star']);
				$v['star_num'] = sprintf("%.1f", $v['star']);

				$v['create_time'] = time_format($v['create_time'], 'm/d H:i');
			}
			api_return(1, '获取数据成功', $comment_list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 视频详情
	 * */
	public function videoTreeDetail()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];

		if (empty($id)) api_return(2, '视频ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('video_tree')->field('id,vc_id,key,name,duration,look_time')->where(array('id' => $id))->find();
		if (empty($info)) api_return(2, '视频不存在或已删除');
		$info['duration'] = intval($info['duration']);

		vendor('qiniuyun/autoload');
		//私有空间视频播放链接
		$accessKey = C('AK');  //秘钥
		$secretKey = C('SK');  //秘钥
		$auth = new Auth($accessKey, $secretKey);  //实例化
		$url = $auth->privateDownloadUrl(C('CDN_URL') . $info['key'], 3600 * 24 * 30);
		$info['url'] = $url;

		//查询课程费用信息
		$price = M('video_course')->where(array('id' => $info['vc_id']))->getField('price');

		$vc_id = M('video_course')->where(array('copy_id' => $info['vc_id']))->getField('id');
		$user_video_course_info = M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $vc_id))->find();
		if ($price > 0) {
			if (empty($user_video_course_info)) {
				$look_auth = 0;
			} else {
				$look_auth = $user_video_course_info['look_auth'];
			}
		} else {
			$look_auth = 1;
		}

		$play_duration = 0;
		$is_collect = 0;

		//课程目录
		$video_tree = M('video_tree')->field('id,name')->where(array('vc_id' => $info['vc_id'], 'pid' => 0))->order('id asc')->select();
		if ($video_tree) {
			foreach ($video_tree as &$v) {
				$video_tree_son = M('video_tree')->field('id,name,is_look,duration,look_time')->where(array('vc_id' => $info['vc_id'], 'pid' => $v['id']))->order('id asc')->select();
				if ($video_tree_son) {
					foreach ($video_tree_son as &$val) {
						$val['duration'] = durationFormat($val['duration']);
						if ($val['id'] == $id) $info['is_look'] = $val['is_look'];

						//是否收藏
						$collect_count = M('collect')->where(array('uid' => $uid, 'to_id' => $val['id'], 'type' => 2, 'is_collect' => 1))->count();
						$collect = $collect_count > 0 ? 1 : 0;
						$val['is_collect'] = $collect;
						if ($val['id'] == $id) $is_collect = $collect;

						$study_info = M('video_study')->where(array('uid' => $uid, 'vt_id' => $val['id']))->find();
						//初始播放位置处理
						if ($val['id'] == $id && $study_info && $study_info['duration'] < $info['duration']) $play_duration = intval($study_info['duration']);

						if ($look_auth == 0) {
							//没有全程播放的权限
							if ($val['is_look'] == 1) {
								$show = 1;
								$show_desc = '试看';
							} else if ($val['is_look'] == 2) {
								if ($study_info) {
									if ($study_info['status'] == 0) {
										$show = 2;
										$show_desc = '学习中';
									} else {
										$show = 3;
										$show_desc = '已学习';
									}
								} else {
									//未学习
									$show = 4;
									$show_desc = '';
								}
							} else {
								//不可观看
								$show = 5;
								$show_desc = '不可观看 - ' . $look_auth . ' - ' . $val['is_look'];
							}
						} else {
							if ($study_info) {
								if ($study_info['status'] == 0) {
									$show = 2;
									$show_desc = '学习中';
								} else {
									$show = 3;
									$show_desc = '已学习';
								}
							} else {
								//未学习
								$show = 4;
								$show_desc = '';
							}
							$val['is_look'] = 2;
						}

						$val['show'] = $show;
						$val['show_desc'] = $show_desc;
					}
				}
				$v['video_tree_son'] = $video_tree_son ? $video_tree_son : array();
			}
		} else {
			$video_tree = array();
		}
		$info['play_duration'] = $play_duration;
		$info['is_collect'] = $is_collect;

		//查询是否有习题
		$exercises_count = M('video_tree_exercises')->where(array('vt_id' => $id))->count();
		$info['exercises_count'] = $exercises_count;

		$data = array(
			'info' => $info,
			'video_tree' => $video_tree
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 在线课确认订单页面
	 * */
	public function videoConfirmOrderPageData()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$is_chief = $input['is_chief'] ? $input['is_chief'] : 0;//1：团长，2：团员
		$book_ids = $input['book_ids'];//相关书籍id集合

		if (empty($id)) api_return(2, '课程ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('video_course')->field('id,img,name,price,is_activity')->where(array('id' => $id))->find();

		$info['price'] = getCoursePrice($id, 2, $info['price'], $info['is_activity'], $is_chief);
		$info['img'] = getPicture($info['img']);
		$info['count'] = videoTreeCount($id);

		$book_price = 0;
		if ($book_ids) {
			$book_list = M('video_book')->field('id,img,name,spec,price')->where(array('id' => array('IN', $book_ids)))->select();
			if ($book_list) {
				foreach ($book_list as &$v) {
					$v['img'] = getPicture($v['img']);
					$v['spec'] = implode('；', json_decode($v['spec'], true));

					$book_price += $v['price'];
				}
			} else {
				$book_list = array();
			}
		} else {
			$book_list = array();
		}

		//默认收货地址
		$default_address = M('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(array('uid' => $uid))->order('is_default desc,id desc')->find();
		$default_address['address'] = getProvinceName($default_address['province_id']) . getCityName($default_address['city_id']) . getAreaName($default_address['area_id']) . $default_address['address'];
		unset($default_address['province_id']);
		unset($default_address['city_id']);
		unset($default_address['area_id']);

		$pay_type_arr = array(
			array(
				'id' => 1,
				'name' => '微信支付'
			)
		);

		$send_type_arr = array(
			array(
				'id' => 1,
				'name' => '快递免邮'
			)
		);

		//优惠券列表
		$empty_coupon_list = array(
			array(
				'id' => 0,
				'name' => '请选择优惠券',
				'deduct_price' => 0
			)
		);
		$user_coupon_list = getUserCoupon($uid, $info['price'], 2);
		$user_coupon_list = $user_coupon_list ? array_merge($empty_coupon_list, $user_coupon_list) : $empty_coupon_list;

		$data = array(
			'info' => $info,
			'book_list' => $book_list,
			'all_price' => $info['price'] + $book_price,
			'address' => $default_address ? $default_address : array(),
			'pay_type_arr' => $pay_type_arr,
			'send_type_arr' => $send_type_arr,
			'user_coupon_list' => $user_coupon_list
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 在线课立即支付
	 * */
	public function payVideoCourse()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$is_chief = $input['is_chief'] ? $input['is_chief'] : 0;
		$pid = $input['pid'] ? $input['pid'] : 0;
		$address_id = $input['address_id'] ? $input['address_id'] : 0;
		$book_ids = $input['book_ids'] ? $input['book_ids'] : '';
		$user_coupon_id = $input['user_coupon_id'] ? $input['user_coupon_id'] : 0;

		if (empty($id)) api_return(2, '在线课ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if ($book_ids && empty($address_id)) api_return(2, '请选择收货地址');

		$info = M('video_course')->where(array('id' => $id))->find();
		if ($info) {
			$model = M();
			$model->startTrans();

			$price = getCoursePrice($id, 2, $info['price'], $info['is_activity'], $is_chief);

			try {
				$book_price = 0;
				if ($book_ids) {
					$book_list = $model->table('teach_video_book')->where(array('id' => array('IN', $book_ids)))->select();
					if ($book_list) {
						foreach ($book_list as &$v) {
							$book_price += $v['price'];
						}
					}
				}

				$pay_order_sn = 'PAY' . date('Ymd') . rand(1000, 9999) . $uid;
				$video_order_sn = 'VIDEO' . date('Ymd') . rand(1000, 9999) . $uid;
				$book_order_sn = 'SN' . date('Ymd') . rand(1000, 9999) . $uid;
				$user_info = $model->table('teach_ucenter_member')->field('iid,share_uid,openid')->where(array('id' => $uid))->find();

				//在线课真实支付价格
				if ($user_coupon_id) {
					$coupon_info = $model->table('teach_user_coupon uc')->join('teach_coupon c ON uc.cid = c.id')->field('c.id,c.deduct_price')->where(array('uc.id' => $user_coupon_id))->find();
					$video_pay_price = $price - $coupon_info['deduct_price'];
				} else {
					$video_pay_price = $price;
				}

				$time = time();

				$address_info = M('address')->where(array('id' => $address_id))->find();

				$back_order_id = '';

				//生成在线课待支付订单
				$video_data = array(
					'iid' => $user_info['iid'],
					'uid' => $uid,
					'order_sn' => $video_order_sn,
					'pay_order_sn' => $pay_order_sn,
					'all_price' => $price,
					'pay_price' => $video_pay_price,
					'user_coupon_id' => $user_coupon_id,
					'type' => 3,
					'share_uid' => $user_info['share_uid'] ? $user_info['share_uid'] : 0,
					'create_time' => $time
				);
				$video_order_id = $model->table('teach_order')->add($video_data);
				$back_order_id = $video_order_id;

				//在线课订单副表数据录入
				$vice_video_data = array(
					'order_id' => $video_order_id,
					'to_id' => $id,
					'img' => $info['img'],
					'name' => $info['name'],
					'old_price' => $info['price'],
					'price' => $video_pay_price,
					'count' => 1,
					'style' => $info['is_activity'],
					'create_time' => $time
				);
				$video_vice_res = $model->table('teach_vice_order')->add($vice_video_data);

				if ($book_list) {
					//生成商品待支付订单
					$goods_data = array(
						'uid' => $uid,
						'order_sn' => $book_order_sn,
						'pay_order_sn' => $pay_order_sn,
						'all_price' => $book_price,
						'pay_price' => $book_price,
						'type' => 4,
						'get_username' => $address_info['username'],
						'get_mobile' => $address_info['mobile'],
						'get_province' => getProvinceName($address_info['province_id']),
						'get_city' => getCityName($address_info['city_id']),
						'get_area' => getAreaName($address_info['area_id']),
						'get_address' => $address_info['address'],
						'share_uid' => getShareUid($uid),
						'create_time' => time()
					);
					$goods_order_id = $model->table('teach_order')->add($goods_data);
					$back_order_id .= ',' . $goods_order_id;

					//生成商品支付副表数据
					$vice_goods_data = array();
					foreach ($book_list as &$v) {
						$vice_goods_data[] = array(
							'order_id' => $goods_order_id,
							'to_id' => $v['id'],
							'img' => $v['img'],
							'name' => $v['name'],
							'spec' => $v['spec'],
							'price' => $v['price'],
							'count' => 1,
							'create_time' => $time
						);
					}
					$vice_book_res = $model->table('teach_vice_order')->addAll($vice_goods_data);
				} else {
					$goods_order_id = true;
					$vice_book_res = true;
				}

				$surplus_res = true;
				$add_skill_res = true;
				$up_order = true;
				$group_join_res = true;
				if ($info['is_activity'] == 2) {
					//秒杀
					$skill_id = M('seckill')->where(array('category' => 2, 'course_id' => $id, 'status' => 1))->getField('id');

					$skill_data = array(
						'uid' => $uid,
						'category' => $info['is_activity'],
						'course_id' => $id,
						'seckill_id' => $skill_id
					);
					$skill_log_info = $model->table('teach_seckill_log')->where($skill_data)->find();

					//删除无效订单
					if ($skill_log_info && $skill_log_info['status'] == 0) {
						$del_order_id = getDbFieldValue('order', array('skill_log_id' => $skill_log_info['id']), 'id');

						//删除无效的秒杀记录
						$model->table('teach_seckill_log')->where($skill_data)->delete();
						//删除无效的订单
						$model->table('teach_order')->where(array('id' => $del_order_id))->delete();
						$model->table('teach_vice_order')->where(array('order_id' => $del_order_id))->delete();

						$model->table('teach_seckill')->where(array('id' => $skill_id))->setInc('surplus_count');
					}

					$add_skill_res = $model->table('teach_seckill_log')->add($skill_data);

					$up_order = $model->table('teach_order')->where(array('id' => $video_order_id))->setField('skill_log_id', $add_skill_res);

					//扣秒杀库存
					$surplus_res = $model->table('teach_seckill')->lock(true)->where(array('id' => $skill_id))->setDec('surplus_count');
				} else if ($info['is_activity'] == 1) {
					//团购
					$work_info = M('group_work')->where(array('course_id' => $id, 'category' => 2, 'status' => 1))->find();
					if ($work_info) {
						//删除无效拼团
						$join_id = getDbFieldValue('group_join', array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0), 'id');
						if ($join_id) {
							$order_id = getDbFieldValue('order', array('group_join_id' => $join_id), 'id');

							M('group_join')->where(array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0))->delete();
							//删除无效拼团产生的订单
							if ($join_id) M('order')->where(array('group_join_id' => $join_id))->delete();
							if ($order_id) M('vice_order')->where(array('order_id' => $order_id))->delete();
						}

						$group_join_data = array(
							'uid' => $uid,
							'pid' => $pid,
							'gid' => $work_info['id'],
							'is_chief' => $is_chief,
							'create_time' => time()
						);
						//新增参团数据
						$group_join_res = $model->table('teach_group_join')->add($group_join_data);
						//修改订单表参团id关联
						$up_order = $model->table('teach_order')->where(array('id' => $video_order_id))->setField('group_join_id', $group_join_res);

						if ($is_chief == 1) {
							//发起拼团，添加redis集合，到了拼团结束时间就自动执行相关程序
							$redisCtr = A('Home/Redis');
							$task_param = array(
								'group_join_id' => $group_join_res,
								'category' => 2,
								'course_id' => $id
							);
							//添加结束执行的redis记录到集合
							$redisCtr->addRedis('groupChiefEnd', time() + $work_info['time_limit'] * 60, $task_param);
						}
					}
				}

				Vendor('pay.pay');
				$data = array(
//					'amount' => floatval(0.05) * 100,
					'amount' => ($video_pay_price + $book_price) * 100,
					'body' => '在线课程支付',
					'description' => '在线课程支付',
					'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/videoNotice',
					'out_trade_no' => $pay_order_sn,
					'channel' => 'WECHAT',
					'product' => 'WECHAT_LITE',
					'subject' => $info['name']
				);
				$appid = C('XCX_APPID');
				$obj = new \pay($data, $appid, $user_info['openid']);

				$recceivers = getRecceivers($order_id ? $order_id : $video_order_id);
				$pay_info = $obj->xcxPay($recceivers);

				if ($video_order_id && $video_vice_res && $goods_order_id && $vice_book_res && $surplus_res && $add_skill_res && $up_order && $group_join_res) {
					$model->commit();

					$pay_info['data']['order_id'] = $back_order_id;
					api_return(1, '生成待支付订单成功', $pay_info['data']);
				} else {
					$model->rollback();
					api_return(2, '生成订单失败');
				}
			} catch (\Exception $e) {
				api_return(2, '系统繁忙，请稍后再试~');
			}
		} else {
			if (empty($uid)) api_return(2, '在线课程不存在或已删除');
		}
	}

	/**
	 * 视频习题列表
	 * */
	public function videoExercisesList()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '视频ID缺失');

		$list = M('video_tree_exercises vte')->join('teach_exercises e ON vte.exercises_id = e.id')->field('vte.id,vte.vt_id,e.question,e.analysis,e.style,e.option')->where(array('vte.vt_id' => $id))->select();
		if ($list) {
			foreach ($list as $key => &$v) {
				$v['list_index'] = $key + 1;
				$v['look_answer'] = false;
				$option = json_decode($v['option'], true);

				$true_answer = '';
				foreach ($option as $val) {
					if ($val['answer']) {
						if ($true_answer == '') {
							$true_answer = $val['key'];
						} else {
							$true_answer .= ',' . $val['key'];
						}
					}
					$v['true_answer'] = $true_answer;
				}
				$v['option'] = $option;
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无数据');
		}
	}

	/**
	 * 记录视频观看时长
	 * */
	public function addStudyLog()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$vc_id = $input['vc_id'];
		$vt_id = $input['vt_id'];
		$duration = $input['duration'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($vc_id)) api_return(2, '课程ID缺失');
		if (empty($vt_id)) api_return(2, '视频ID缺失');
		if (empty($duration)) api_return(2, '观看时长缺失');

		$time = time();

		$vc_id = M('video_course')->where(array('copy_id' => $vc_id))->getField('id');

		$map = ' expire_time > ' . $time . ' || expire_time = 0';

		$user_course_count = M('user_video_course')->where(array('uid' => $uid, 'vc_id' => $vc_id))->where($map)->count();
		if ($user_course_count) {
			$section_count = getTreeSection($vc_id, $vt_id);
			$count = M('video_study')->where(array('uid' => $uid, 'vc_id' => $vc_id, 'vt_id' => $vt_id))->count();
			if ($count) {
				$data = array(
					'duration' => $duration,
					'study_time' => $time,
					'date' => date('Y-m-d'),
					'section' => $section_count,
				);

				$res = M('video_study')->where(array('uid' => $uid, 'vc_id' => $vc_id, 'vt_id' => $vt_id))->save($data);
			} else {
				$data = array(
					'uid' => $uid,
					'vc_id' => $vc_id,
					'vt_id' => $vt_id,
					'duration' => $duration,
					'study_time' => $time,
					'date' => date('Y-m-d'),
					'section' => $section_count,
					'create_time' => $time
				);
				$res = M('video_study')->add($data);
			}

			if ($res) {
				api_return(1, '记录成功');
			} else {
				api_return(2, '记录失败');
			}
		}
	}

	/**
	 * 增加用户学习时长
	 * */
	public function incUserStudyTime()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$time = $input['time'];//学习时长（秒）

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$user_info = M('ucenter_member')->field('all_study_time,today_study_time')->where(array('id' => $uid))->find();

		$data = array(
			'all_study_time' => $user_info['all_study_time'] + $time,
			'today_study_time' => $user_info['today_study_time'] + $time
		);

		M('ucenter_member')->where(array('id' => $uid))->save($data);
	}

	/**
	 * 在线课视频提问
	 * */
	public function videoQuestion()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$question = $input['question'];
		$imgs = $input['imgs'];

		if (empty($id)) api_return(2, '视频ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($question)) api_return(2, '请输入您的问题');

		$data = array(
			'vt_id' => $id,
			'uid' => $uid,
			'question' => $question,
			'imgs' => $imgs,
			'create_time' => time()
		);
		$res = M('video_question')->add($data);
		if ($res) {
			api_return(1, '提交成功');
		} else {
			api_return(2, '提交失败');
		}
	}

	/**
	 * 我的提问
	 * */
	public function questionList()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];

		if (empty($id)) api_return(2, '视频ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$list = M('video_question')->field('id,question,imgs,answer,create_time')->where(array('vt_id' => $id, 'uid' => $uid))->order('id desc')->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['imgs'] = doImgs($v['imgs']);
				$v['create_time'] = time_format($v['create_time'], 'Y-m-d');
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无数据');
		}
	}

	/**
	 * 收藏 整个课程/单个课程/题目
	 * */
	public function collect()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$to_id = $input['to_id'];
		$type = $input['type'];//1：整个课程，2：单个课程，3：题目
		$is_collect = $input['is_collect'];//0：取消收藏，1：收藏

		$info = M('collect')->where(array('uid' => $uid, 'to_id' => $to_id, 'type' => $type))->find();
		if ($info) {
			if ($info['is_collect'] == $is_collect) {
				api_return(2, '系统繁忙，请稍后再试');
			} else {
				$data = array(
					'is_collect' => $is_collect,
					'update_time' => time(),
					'create_time' => time()
				);
				$res = M('collect')->where(array('id' => $info['id']))->save($data);
				$msg = $is_collect == 0 ? '取消收藏' : '收藏';
				if ($res) {
					api_return(1, $msg . '成功');
				} else {
					api_return(2, $msg . '失败');
				}
			}
		} else {
			if ($is_collect == 0) {
				api_return(2, '系统繁忙，请稍后再试');
			} else {
				if ($type == 3) {
					$sid = M('practice')->where(array('id' => $to_id))->getField('sid');
				} else {
					$sid = 0;
				}

				$data = array(
					'uid' => $uid,
					'sid' => $sid,
					'to_id' => $to_id,
					'type' => $type,
					'is_collect' => $is_collect,
					'create_time' => time()
				);
				$res = M('collect')->add($data);
				if ($res) {
					api_return(1, '收藏成功');
				} else {
					api_return(2, '收藏失败');
				}
			}
		}
	}

	/**
	 * 面授课列表
	 * */
	public function faceList()
	{
		$input = I('post.');

		$iid = $input['iid'];//机构id
		$name = $input['name'];
		$one_type_id = $input['one_type_id'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($iid)) api_return(2, '请先绑定机构');

		$empty_list = array(
			array(
				'id' => 0,
				'name' => '特别推荐',
				'active' => 1
			)
		);
		$type_list = M('face_course_type')->field('id,name')->where(array('pid' => 0))->order('sort asc')->select();
		if ($type_list) {
			foreach ($type_list as &$v) {
				$v['active'] = 0;
			}
		} else {
			$type_list = array();
		}
		$type_list = array_merge($empty_list, $type_list);

		$where['iid'] = $iid;
		$where['end_enlist_time'] = array('gt', time());
		$where['is_activity'] = 0;
		$where['is_upper'] = 1;
		$where['is_del'] = 0;
		if ($one_type_id) $where['one_type_id'] = $one_type_id;
		if ($name) $where['name'] = array('LIKE', '%' . $name . '%');
		$list = M('face_course')->field('id,img,name,price,count')->where($where)->page($page, $pagesize)->order('id desc')->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);
			}
		} else {
			$list = array();
		}
		$data = array(
			'type_list' => $type_list,
			'list' => $list
		);
		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 面授课详情
	 * */
	public function faceDetail()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$share_uid = $input['share_uid'] ? $input['share_uid'] : 0;

		if (empty($id)) api_return(2, '课程ID缺失');

		$info = M('face_course')->field('id,img,name,price,count,enlist_count,start_date,end_date,study_time,province_id,city_id,area_id,address,teacher_ids,desc,catalog,end_enlist_time,is_activity')->where(array('id' => $id))->find();
		if ($info) {
			$info['img'] = getPicture($info['img']);
			$info['address'] = getProvinceName($info['province_id']) . getCityName($info['city_id']) . getAreaName($info['area_id']) . $info['address'];
			$info['study_time'] = json_decode($info['study_time'], true);
			$info['time'] = json_decode($info['time'], true);

			$info['desc'] = str_replace('<img src="', '<img style="width: 100%; height: auto" src="' . getHost(), $info['desc']);
			$info['catalog'] = json_decode($info['catalog'], true);

			if ($info['teacher_ids']) {
				$teacher_list = M('teacher')->field('id,avatar_id,name,sign')->where(array('id' => array('IN', $info['teacher_ids'])))->select();
				if ($teacher_list) {
					foreach ($teacher_list as &$v) {
						$v['avatar'] = getPicture($v['avatar_id']);
					}
				}
			} else {
				$teacher_list = array();
			}
			$info['teacher_list'] = $teacher_list;

			//获取活动数据
			$activity_course_info = getActivityCourseInfo($id, 1, $info['price'], $info['is_activity']);
			$info['group_len'] = count($activity_course_info['group_list']);
			$info['group_list'] = $activity_course_info['group_list'];
			$info['all_group_people'] = $activity_course_info['all_group_people'];
			$info['price'] = $activity_course_info['price'];

			//按钮控制；1：立即购买，2：发起拼团，3：参与拼团，4：立即秒杀，5：不显示按钮
			$user_face_count = M('order o')->join('teach_vice_order vc ON o.id = vc.order_id')->where(array('o.uid' => $uid, 'o.type' => 2, 'o.is_pay' => 1, 'vc.to_id' => $id))->count();
			if ($user_face_count > 0 || $info['end_enlist_time'] < time()) {
				//严格控制用户之前购买面授课程的情况下不能再次购买
				$info['btn'] = 5;
				$info['btn_name'] = '';
			} else {
				if ($info['is_activity'] == 0) {
					//无活动
					$info['btn'] = 1;
					$info['btn_name'] = '立即购买';
				} else if ($info['is_activity'] == 1) {
					//团购活动
					$work_info = M('group_work')->where(array('course_id' => $id, 'category' => 1, 'status' => 1))->find();
					if ($work_info) {
						$info['group_price'] = $work_info['group_price'];
						$info['chief_price'] = $work_info['chief_price'];

						//团ID，供底部参与拼团按钮使用
						if ($share_uid > 0) {
							$chief_group_join_info = M('group_join')->where(array('uid' => $share_uid, 'gid' => $work_info['id']))->find();
							$group_join_pid = $chief_group_join_info['is_chief'] == 1 ? $chief_group_join_info['id'] : $chief_group_join_info['pid'];
							$info['group_join_pid'] = $group_join_pid ? $group_join_pid : 0;

							//隐藏底部【参与拼团】按钮，原因，用户分享的这个团人数满了
							if ($chief_group_join_info['status'] == 2) $info['hide_btn'] = true;
						}
					}

					$join_count = M('group_join')->where(array('gid' => $work_info['id'], 'uid' => $uid, 'status' => array('IN', '1,2')))->count();
					if ($join_count == 0) {
						//团个数
						$chief_count = M('group_join')->where(array('gid' => $work_info['id'], 'pid' => 0, 'status' => array('IN', '1,2')))->count();
						if ($chief_count >= $work_info['group_limit_number'] && $chief_count > 0) {
							$info['btn'] = 3;
							$info['btn_name'] = '参与拼团';
						} else {
							if ($share_uid > 0) {
								//查询分享者是否在团中
								$share_join_count = M('group_join')->where(array('gid' => $work_info['id'], 'uid' => $share_uid, 'status' => array('IN', '1,2')))->count();
								if ($share_join_count > 0) {
									$info['btn'] = 3;
									$info['btn_name'] = '参与拼团';
								} else {
									$info['btn'] = 2;
									$info['btn_name'] = '发起拼团';
								}
							} else {
								$info['btn'] = 2;
								$info['btn_name'] = '发起拼团';
							}
						}
					} else {
						$info['btn'] = 5;
						$info['btn_name'] = '';
					}
				} else {
					//秒杀活动
					if ($user_face_count > 0) {
						$info['btn'] = 5;
						$info['btn_name'] = '';
					} else {
						//秒杀活动
						$info['btn'] = 4;
						$info['btn_name'] = '立即秒杀';
					}
				}
			}

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '课程不存在或已删除');
		}
	}

	/**
	 * 面授报名详情
	 * */
	public function faceEnlistInfo()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$is_chief = $input['is_chief'] ? $input['is_chief'] : 0;//1：团长，2：团员

		if (empty($id)) api_return(2, '面授课ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('face_course')->field('id,name,img,count,price,is_activity')->where(array('id' => $id))->find();
		if ($info) {
			$info['img'] = getPicture($info['img']);

			//优惠券列表
			$empty_coupon_list = array(
				array(
					'id' => 0,
					'name' => '请选择优惠券',
					'deduct_price' => 0
				)
			);
			$user_coupon_list = getUserCoupon($uid, $info['price'], 1);
			$info['user_coupon_list'] = $user_coupon_list ? array_merge($empty_coupon_list, $user_coupon_list) : $empty_coupon_list;

			$pay_type_arr = array(
				array(
					'id' => 1,
					'name' => '微信支付'
				)
			);
			$info['pay_type_arr'] = $pay_type_arr;

			if ($info['is_activity'] > 0) $info['price'] = getCoursePrice($info['id'], 1, $info['price'], $info['is_activity'], $is_chief);

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '面授课不存在或已删除');
		}
	}

	/**
	 * 面授课程立即支付
	 * */
	public function payFaceCourse()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$is_chief = $input['is_chief'] ? $input['is_chief'] : 0;
		$pid = $input['pid'] ? $input['pid'] : 0;
		$user_coupon_id = $input['user_coupon_id'] ? $input['user_coupon_id'] : 0;

		if (empty($id)) api_return(2, '课程ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('face_course')->where(array('id' => $id))->find();
		if ($info) {
			$model = M();
			$model->startTrans();

			$price = getCoursePrice($id, 1, $info['price'], $info['is_activity'], $is_chief);

			try {
				$order_sn = 'FACE' . date('Ymd') . rand(1000, 9999) . $uid;
				$user_info = $model->table('teach_ucenter_member')->field('iid,share_uid,openid')->where(array('id' => $uid))->find();

				if ($user_coupon_id) {
					$coupon_info = $model->table('teach_user_coupon uc')->join('teach_coupon c ON uc.cid = c.id')->field('c.id,c.deduct_price')->where(array('uc.id' => $user_coupon_id))->find();
					$pay_price = $price - $coupon_info['deduct_price'];
				} else {
					$pay_price = $price;
				}

				//生成待支付订单
				$data = array(
					'iid' => $user_info['iid'],
					'uid' => $uid,
					'order_sn' => $order_sn,
					'pay_order_sn' => $order_sn,
					'all_price' => $price,
					'pay_price' => $pay_price,
					'user_coupon_id' => $user_coupon_id,
					'type' => 2,
					'share_uid' => $user_info['share_uid'] ? $user_info['share_uid'] : 0,
					'create_time' => time()
				);
				$order_id = $model->table('teach_order')->add($data);

				$vice_data = array(
					'order_id' => $order_id,
					'to_id' => $id,
					'img' => $info['img'],
					'name' => $info['name'],
					'price' => $pay_price,
					'count' => 1,
					'style' => $info['is_activity'],
					'create_time' => time()
				);
				$vice_res = $model->table('teach_vice_order')->add($vice_data);

				$surplus_res = true;
				$add_skill_res = true;
				$up_order = true;
				$group_join_res = true;
				if ($info['is_activity'] == 2) {
					//秒杀
					$skill_id = M('seckill')->where(array('category' => 1, 'course_id' => $id, 'status' => 1))->getField('id');

					$skill_data = array(
						'uid' => $uid,
						'category' => $info['is_activity'],
						'course_id' => $id,
						'seckill_id' => $skill_id
					);
					$skill_log_info = $model->table('teach_seckill_log')->where($skill_data)->find();

					//删除无效订单
					if ($skill_log_info && $skill_log_info['status'] == 0) {
						$del_order_id = getDbFieldValue('order', array('skill_log_id' => $skill_log_info['id']), 'id');

						//删除无效的秒杀记录
						$model->table('teach_seckill_log')->where($skill_data)->delete();
						//删除无效的订单
						$model->table('teach_order')->where(array('id' => $del_order_id))->delete();
						$model->table('teach_vice_order')->where(array('order_id' => $del_order_id))->delete();

						$model->table('teach_seckill')->where(array('id' => $skill_id))->setInc('surplus_count');
					}

					$add_skill_res = $model->table('teach_seckill_log')->add($skill_data);

					$up_order = $model->table('teach_order')->where(array('id' => $order_id))->setField('skill_log_id', $add_skill_res);

					//扣秒杀库存
					$surplus_res = $model->table('teach_seckill')->lock(true)->where(array('id' => $skill_id))->setDec('surplus_count');
				} else if ($info['is_activity'] == 1) {
					//团购
					$work_info = M('group_work')->where(array('course_id' => $id, 'category' => 1, 'status' => 1))->find();
					if ($work_info) {
						//删除无效拼团
						M('group_join')->where(array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0))->find();

						$join_id = getDbFieldValue('group_join', array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0), 'id');
						if ($join_id) {
							$del_order_id = getDbFieldValue('order', array('group_join_id' => $join_id), 'id');

							M('group_join')->where(array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0))->delete();
							//删除无效拼团产生的订单
							if ($join_id) M('order')->where(array('group_join_id' => $join_id))->delete();
							if ($del_order_id) M('vice_order')->where(array('order_id' => $del_order_id))->delete();
						}

						$group_join_data = array(
							'uid' => $uid,
							'pid' => $pid,
							'gid' => $work_info['id'],
							'is_chief' => $is_chief,
							'create_time' => time()
						);
						//新增参团数据
						$group_join_res = $model->table('teach_group_join')->add($group_join_data);
						//修改订单表参团id关联
						$up_order = $model->table('teach_order')->where(array('id' => $order_id))->setField('group_join_id', $group_join_res);

						if ($is_chief == 1) {
							//发起拼团，添加redis集合，到了拼团结束时间就自动执行相关程序
							$redisCtr = A('Home/Redis');
							$task_param = array(
								'group_join_id' => $group_join_res,
								'category' => 1,
								'course_id' => $id
							);
							//添加结束执行的redis记录到集合
							$redisCtr->addRedis('groupChiefEnd', time() + $work_info['time_limit'] * 60, $task_param);
						}
					}
				}

				Vendor('pay.pay');
				$data = array(
					'amount' => floatval(0.05) * 100,
					//'amount' => floatval($pay_price) * 100,
					'body' => '面授课程支付',
					'description' => '面授课程支付',
					'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/faceNotice',
					'out_trade_no' => $order_sn,
					'channel' => 'WECHAT',
					'product' => 'WECHAT_LITE',
					'subject' => $info['name']
				);
				$appid = C('XCX_APPID');
				$obj = new \pay($data, $appid, $user_info['openid']);

				//获取分账人信息
				$receivers = getRecceivers($order_id);
				$pay_info = $obj->xcxPay($receivers);

				if ($order_id && $vice_res && $surplus_res && $add_skill_res && $up_order && $group_join_res) {
					$model->commit();

					$pay_info['data']['order_id'] = $order_id;
					api_return(1, '生成待支付订单成功', $pay_info['data']);
				} else {
					$model->rollback();
					api_return(2, '生成订单失败');
				}
			} catch (\Exception $e) {
				api_return(2, '系统繁忙，请稍后再试~' . $e);
			}
		} else {
			if (empty($uid)) api_return(2, '面授课程不存在或已删除');
		}
	}

	/**
	 * 商品分类
	 * */
	public function goodsType()
	{
		$empty_arr = array(
			array(
				'id' => 0,
				'name' => '特别推荐',
				'active' => 1,
				'son_type_list' => array(
					array(
						'id' => 0,
						'name' => '全部',
						'active' => 0
					)
				)
			)
		);
		$type_list = M('goods_type')->field('id,name')->where(['pid' => 0])->order('sort asc')->select();
		if ($type_list) {
			foreach ($type_list as &$v) {
				$v['active'] = 0;

				$son_empty_arr = array(
					array(
						'id' => 0,
						'name' => '全部',
						'active' => 0
					)
				);

				$son_type_list = M('goods_type')->field('id,name')->where(['pid' => $v['id']])->order('sort asc')->select();
				if ($son_type_list) {
					foreach ($son_type_list as &$val) {
						$val['active'] = 0;
					}
				}
				$son_type_list = array_merge($son_empty_arr, $son_type_list);

				$v['son_type_list'] = $son_type_list;
			}
		}
		$type_list = array_merge($empty_arr, $type_list);

		api_return(1, '获取数据成功', $type_list);
	}

	/**
	 * 商品列表
	 * */
	public function goodsList()
	{
		$input = I('post.');
		$name = $input['name'];
		$one_type_id = $input['one_type_id'];//-1：推荐，0：全部，大于0：一级分类id
		$two_type_id = $input['two_type_id'];//0：全部，大于0：二级分类id
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		$where['is_del'] = 0;
		$where['is_recommend'] = 1;//小程序显示的书籍都是由后台推荐的

		if ($name) $where['name'] = array('LIKE', '%' . $name . '%');
		if ($one_type_id > 0) $where['one_type_id'] = $one_type_id;
		if ($two_type_id > 0) $where['two_type_id'] = $two_type_id;

		$list = M('goods')->field('id,name,short_desc,imgs,min_price,max_price,sales_count')->where($where)->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$imgs = doImgs($v['imgs']);
				$v['img'] = $imgs[0]['path'];
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 商品详情
	 * */
	public function goodsDetail()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '商品ID缺失');

		$info = M('goods')->field('id,name,imgs,short_desc,press,min_price,max_price,average,tags,detail,spec')->where(array('id' => $id))->find();
		if ($info) {
			$info['average'] = floatval($info['average']);
			$info['imgs'] = doImgs($info['imgs']);
			$info['img'] = $info['imgs'][0]['path'];
			$info['tags'] = $info['tags'] ? explode(',', $info['tags']) : [];
			$info['spec'] = json_decode($info['spec']);
			$info['detail'] = str_replace('<img src="', '<img style="width: 100%; height: auto" src="' . getHost(), $info['detail']);

			if ($info['min_price'] == $info['max_price']) {
				$info['price'] = $info['min_price'];
			} else {
				$info['price'] = $info['min_price'] . '-' . $info['max_price'];
			}

			//库存数
			$goods_count = M('goods_spec')->where(array('goods_id' => $id))->sum('count');
			$info['goods_count'] = $goods_count;

			//规格信息
			$spec_list = M('goods_spec')->field('id,img,spec,price,count')->where(array('goods_id' => $id))->select();
			if ($spec_list) {
				foreach ($spec_list as &$v) {
					$v['img'] = getPicture($v['img']);
				}
			} else {
				$spec_list = array();
			}
			$info['spec_list'] = $spec_list;

			//评论
			$comment_list = M('comment')->field('id,uid,star,content,create_time')->where(array('to_id' => $id, 'type' => 2, 'status' => 1))->select();
			if ($comment_list) {
				foreach ($comment_list as &$v) {
					$v['star'] = intval($v['star']);
					$v['create_time'] = time_format($v['create_time'], 'y-m H:i');

					$user_info = M('ucenter_member')->field('avatar,username')->where(array('id' => $v['uid']))->find();
					$v['avatar'] = doAvatar($user_info['avatar']);
					$v['username'] = $user_info['username'];
				}
			} else {
				$comment_list = array();
			}
			$info['comment_list'] = $comment_list;

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '商品不存在或已删除');
		}
	}

	/**
	 * 商品确认订单
	 * */
	public function confirmOrder()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$spec_id = $input['spec_id'];
		$count = $input['count'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($spec_id)) api_return(2, '商品规格ID缺失');
		if (empty($count)) api_return(2, '商品数量异常');

		$spec_list = M('goods_spec')->field('id,img,price,spec,goods_id')->where(array('id' => $spec_id))->select();
		if ($spec_list) {
			foreach ($spec_list as &$v) {
				$goods_name = getDbFieldValue('goods', array('id' => $v['goods_id']), 'name');
				$v['goods_name'] = $goods_name;
				$v['img'] = getPicture($v['img']);
				$v['spec'] = implode('；', json_decode($v['spec'], true));
				$all_price = sprintf("%.2f", $v['price'] * $count);
			}

			//默认收货地址
			$default_address = M('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(array('uid' => $uid))->order('is_default desc,id desc')->find();
			$default_address['address'] = getProvinceName($default_address['province_id']) . getCityName($default_address['city_id']) . getAreaName($default_address['area_id']) . $default_address['address'];
			unset($default_address['province_id']);
			unset($default_address['city_id']);
			unset($default_address['area_id']);

			$pay_type_arr = array(
				array(
					'id' => 1,
					'name' => '微信支付'
				)
			);

			$send_type_arr = array(
				array(
					'id' => 1,
					'name' => '快递免邮'
				)
			);

			$data = array(
				'goods_list' => $spec_list,
				'all_price' => $all_price,
				'address' => $default_address ? $default_address : array(),
				'pay_type_arr' => $pay_type_arr,
				'send_type_arr' => $send_type_arr
			);

			api_return(1, '获取数据成功', $data);
		} else {
			api_return(2, '规格不存在或已删除');
		}
	}

	/**
	 * 立即支付【生成待支付订单】 之后 发起支付
	 * */
	public function addGoodsOrder()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$goods_id = $input['goods_id'];
		$count = $input['count'];
		$spec_id = $input['spec_id'];
		$address_id = $input['address_id'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($goods_id)) api_return(2, '商品ID缺失');
		if ($count <= 0) api_return(2, '商品数量异常');
		if (empty($spec_id)) api_return(2, '规格ID缺失');
		if (empty($address_id)) api_return(2, '请选择收货地址');

		$user_info = getUserInfo($uid, 'openid');
		if (empty($user_info)) api_return(2, '用户信息不存在或已删除');

		$goods_info = M('goods')->field('id,name,supplier_id')->where(array('id' => $goods_id))->find();
		if ($goods_info) {
			$spec_info = M('goods_spec')->where(array('id' => $spec_id))->find();
			if ($spec_info) {
				//商品库存
				if ($count > $spec_info['count']) api_return(2, '商品库存不足');

				$address_info = M('address')->where(array('id' => $address_id))->find();

				$all_price = $spec_info['price'] * $count;

				$order_sn = 'SN' . date('Ymd') . rand(1000, 9999) . $uid;
				$iid = getDbFieldValue('ucenter_member', array('id' => $uid), 'iid');
				$share_uid = getShareUid($uid);
				$data = array(
					'iid' => $iid ? $iid : 0,
					'uid' => $uid,
					'supplier_id' => $goods_info['supplier_id'],
					'order_sn' => $order_sn,
					'pay_order_sn' => $order_sn,
					'all_price' => $all_price,
					'pay_price' => $all_price,
					'type' => 4,
					'get_username' => $address_info['username'],
					'get_mobile' => $address_info['mobile'],
					'get_province' => getProvinceName($address_info['province_id']),
					'get_city' => getCityName($address_info['city_id']),
					'get_area' => getAreaName($address_info['area_id']),
					'get_address' => $address_info['address'],
					'share_uid' => $share_uid,
					'create_time' => time()
				);

				$res = M('order')->add($data);
				if ($res) {
					$goods_order = array(
						'order_id' => $res,
						'supplier_id' => $goods_info['supplier_id'],
						'to_id' => $goods_id,
						'img' => $spec_info['img'],
						'name' => $goods_info['name'],
						'spec' => $spec_info['spec'],
						'old_price' => $spec_info['old_price'],
						'price' => $spec_info['price'],
						'count' => $count,
						'create_time' => time()
					);
					M('vice_order')->add($goods_order);

					Vendor('pay.pay');
					$data = array(
//						'amount' => floatval($all_price) * 100,
						'amount' => floatval(0.01) * 100,
						'body' => '商品支付',
						'description' => '商品支付',
						'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/goodsNotice',
						'out_trade_no' => $order_sn,
						'product' => 'WECHAT_LITE',
						'subject' => $goods_info['name']
					);
					$appid = C('XCX_APPID');
					$openid = $user_info['openid'];
					$obj = new \pay($data, $appid, $openid);

					$recceivers = getRecceivers($res);
					$result = $obj->xcxPay($recceivers);

					$return_data = array(
						'pay_data' => $result['data'],
						'order_id' => $res
					);

					api_return(1, '获取数据成功', $return_data);
				} else {
					api_return(2, '生成订单失败');
				}
			} else {
				api_return(2, '规格不存在或已删除');
			}
		} else {
			api_return(2, '商品不存在或已删除');
		}
	}

	public function test()
	{
		$arr = array(
			'type' => '1',
			'account' => '1000000155320'
		);

		$receives = array(
			$arr,
			'{"type":"1","account":"1000000155320"}',
			'{"type":"1","account":"1000000155321"}',
			'{"type":"1","account":"1000000155322"}'
		);

		$recceivers = json_encode(array_merge(array_unique($receives, SORT_REGULAR)));

		echo "<pre>";
		print_r($recceivers);
		exit;
	}

	/**
	 * 待支付订单取消订单
	 * */
	public function cancelWaitPayOrder()
	{
		$input = I('post.');

		$order_id = $input['order_id'];

		if ($order_id) {
			M('order_share_price')->where(array('order_id' => $order_id))->delete();

			if (count(explode(',', $order_id)) == 1) {
				//单个订单
				$info = M('order')->where(array('id' => $order_id))->find();
				if ($info['skill_log_id'] > 0) {
					$skill_id = getDbFieldValue('seckill_log', array('id' => $info['skill_log_id']), 'seckill_id');
					if ($skill_id > 0) M('seckill')->where(array('id' => $skill_id))->setInc('surplus_count');
				}

				M('order')->where(array('id' => $order_id))->delete();
				M('vice_order')->where(array('order_id' => $order_id))->delete();

				//删除无效秒杀记录
				if ($info['skill_log_id']) M('seckill_log')->where(array('id' => $info['skill_log_id']))->delete();
				//删除无效团购记录
				if ($info['group_join_id']) M('group_join')->where(array('id' => $info['group_join_id']))->delete();

				api_return(1, '成功');
			} else {
				//多个订单
				$list = M('order')->where(array('id' => array('IN', $order_id)))->select();
				if ($list) {
					M('order')->where(array('id' => array('IN', $order_id)))->delete();
					M('vice_order')->where(array('order_id' => array('IN', $order_id)))->delete();

					foreach ($list as &$v) {
						if ($v['skill_log_id'] > 0) {
							$skill_id = getDbFieldValue('seckill_log', array('id' => $v['skill_log_id']), 'seckill_id');
							if ($skill_id > 0) M('seckill')->where(array('id' => $skill_id))->setInc('surplus_count');
						}

						//删除无效秒杀记录
						if ($v['skill_log_id']) M('seckill_log')->where(array('id' => $v['skill_log_id']))->delete();
						//删除无效团购记录
						if ($v['group_join_id']) M('group_join')->where(array('id' => $v['group_join_id']))->delete();
					}
				}
			}
		}
	}

	/**
	 * 商城取消订单
	 * */
	public function shopCancelOrder()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '订单ID缺失');

		$info = M('order')->where(array('id' => $id, 'is_del' => 0))->find();
		if ($info) {
			Vendor('pay.pay');

			$back_order_sn = 'RE' . date('Ymd') . rand(1000, 9999) . $id;

			$res = M('order')->where(array('id' => $id))->save(array('back_order_sn' => $back_order_sn, 'status' => 7));
			if ($res) {
				$data = array(
					'order_sn' => $info['pay_order_sn'],
					'out_refund_no' => $back_order_sn,
					'amount' => floatval(0.01) * 100,
//					'amount' => floatval($info['pay_price']) * 100,
					'subject' => '商品申请退款',
					'body' => '商品申请退款',
					'description' => '商品申请退款',
					'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/goodsRefundNotice'
				);
				$appid = C('XCX_APPID');
				$user_info = getUserInfo($info['uid'], 'openid');
				$openid = $user_info['openid'];
				$obj = new \pay($data, $appid, $openid);
				$result = $obj->applyRefund();

				api_return(1, '取消订单成功', $result);
			} else {
				api_return(2, '订单取消失败');
			}
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 商城申请售后页面数据回显
	 * */
	public function shopApplyAfterPageData()
	{
		$after_type_list = M('after_data')->field('id,desc,is_back_price')->where(array('type' => 1))->select();
		$after_reason_list = M('after_data')->field('id,desc')->where(array('type' => 2))->select();

		$data = array(
			'after_type_list' => $after_type_list,
			'after_reason_list' => $after_reason_list
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 申请售后
	 * */
	public function applyAfter()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$after_type = $input['after_type'];
		$after_reason = $input['after_reason'];
		$is_back_price = $input['is_back_price'];
		$desc = $input['desc'];

		if (empty($id)) api_return(2, '订单ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($desc)) api_return(2, '请输入原因描述');

		$info = M('order')->where(array('id' => $id))->find();
		if ($info) {
			$model = M();
			$model->startTrans();

			$time = time();
			try {
				$order_data = array(
					'status' => 6,
					'update_time' => $time
				);
				$order_res = $model->table('teach_order')->where(array('id' => $id))->save($order_data);

				$after_data = array(
					'uid' => $uid,
					'order_id' => $id,
					'after_type' => $after_type,
					'after_reason' => $after_reason,
					'is_back_price' => $is_back_price,
					'desc' => $desc,
					'status' => 1,
					'create_time' => $time
				);
				$after_res = $model->table('teach_after')->add($after_data);

				if ($order_res && $after_res) {
					$model->commit();
					api_return(1, '提交成功');
				} else {
					$model->rollback();
					api_return(2, '提交失败');
				}
			} catch (\Exception $e) {
				api_return(2, '系统繁忙，请稍后再试');
			}
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 商城确认收货
	 * */
	public function shopConfirmGetGoods()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '订单ID缺失');

		$info = M('order')->where(array('id' => $id))->find();
		if ($info) {
			$data = array(
				'status' => 3,
				'update_time' => time()
			);
			$res = M('order')->where(array('id' => $id))->save($data);
			if ($res) {
				api_return(1, '确认收货成功');
			} else {
				api_return(2, '确认收货失败');
			}
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 商品评价页面数据
	 * */
	public function goodsCommentPageData()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '订单ID缺失');

		$info = M('order')->where(array('id' => $id, 'is_del' => 0))->find();
		if ($info) {
			$goods_list = M('vice_order')->field('id,to_id,img,name,spec,price,count')->where(array('order_id' => $id))->select();
			if ($goods_list) {
				$comment_list = array();
				foreach ($goods_list as &$v) {
					$v['img'] = getPicture($v['img']);
					$v['spec'] = implode('；', json_decode($v['spec'], true));
					$v['star'] = 5;

					$comment_list[] = array(
						'to_id' => $v['to_id'],
						'star' => 5,
						'content' => ''
					);
				}

				$data = array(
					'goods_list' => $goods_list,
					'comment_list' => $comment_list
				);

				api_return(1, '获取数据成功', $data);
			} else {
				api_return(2, '未查询到订单商品数据');
			}
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 商品评价
	 * */
	public function goodsComment()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$order_id = $input['order_id'];
		$comment_list = json_decode($input['comment_list'], true);

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($order_id)) api_return(2, '订单ID缺失');
		if (empty($comment_list)) api_return(2, '评价数据缺失');

		$info = M('order')->where(array('id' => $order_id, 'is_del' => 0))->find();
		if ($info) {
			$res = M('order')->where(array('id' => $order_id))->save(array('status' => 4, 'update_time' => time()));
			if ($res) {
				$data = array();
				foreach ($comment_list as &$v) {
					$data[] = array(
						'uid' => $uid,
						'order_id' => $order_id,
						'to_id' => $v['to_id'],
						'content' => $v['content'],
						'star' => $v['star'],
						'type' => 2,
						'status' => $v['star'] > 3 ? 1 : 0,
						'create_time' => time()
					);

					$comment_count = M('comment')->where(array('to_id' => $v['to_id'], 'type' => 2, 'status' => 1))->count();
					if ($comment_count > 0) {
						$star = M('comment')->where(array('to_id' => $v['to_id'], 'type' => 2, 'status' => 1))->sum('star');
						$average = ($star + $v['star']) / ($comment_count + 1);
					} else {
						$average = $v['star'];
					}
					M('goods')->where(array('id' => $v['to_id']))->save(array('average' => $average, 'update_time' => time()));
				}
				M('comment')->addAll($data);

				api_return(1, '评价成功');
			} else {
				api_return(2, '评价失败');
			}
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 删除订单
	 * */
	public function delOrder()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '订单ID缺失');

		$info = M('order')->where(array('id' => $id, 'is_del' => 0))->find();
		if ($info) {
			$res = M('order')->where(array('id' => $id))->save(array('is_del' => 1, 'update_time' => time()));
			if ($res) {
				api_return(1, '删除订单成功');
			} else {
				api_return(2, '删除订单失败');
			}
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 购物车商品数量校正
	 * tips：在小程序 onHide 和 onUnload 中调用该接口
	 * */
	public function doCarGoodsCount()
	{
		$input = I('post.');
		$car_list = json_decode($input['car_list'], true);//[{"id":"4","count":"8"}]
		if ($car_list) {
			foreach ($car_list as &$v) {
				M('goods_car')->where(array('id' => $v['id']))->setField('count', $v['count']);
			}
		}
	}

	/**
	 * 加入购物车
	 * */
	public function addGoodsCar()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$goods_id = $input['goods_id'];
		$spec_id = $input['spec_id'];//规格id；goods_spec表主键id
		$count = $input['count'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($goods_id)) api_return(2, '商品ID缺失');
		if (empty($spec_id)) api_return(2, '规格ID缺失');
		if ($count <= 0) api_return(2, '商品数量异常');

		$goods_info = M('goods')->where(array('id' => $goods_id))->find();
		if ($goods_info) {
			$spec_info = M('goods_spec')->field('img,price,spec,count')->where(array('id' => $spec_id))->find();
			if ($spec_info) {
				if ($spec_info['count'] < $count) api_return(2, '商品所选规格库存不足');

				$car_info = M('goods_car')->where(array('uid' => $uid, 'goods_id' => $goods_id, 'spec' => $spec_info['spec']))->find();
				if ($car_info) {
					//该商品之前已经加入过购物车，这个时候只需要增加购物车数量即可
					$res = M('goods_car')->where(array('id' => $car_info['id']))->setInc('count', $count);
				} else {
					//该商品第一次加入购物车，添加购物车数据
					$data = array(
						'uid' => $uid,
						'goods_id' => $goods_id,
						'img' => $spec_info['img'],
						'spec' => $spec_info['spec'],
						'count' => $count,
						'price' => $spec_info['price'],
						'create_time' => time()
					);
					$res = M('goods_car')->add($data);
				}
			} else {
				api_return(2, '规格不存在或已删除');
			}

			if ($res) {
				api_return(1, '添加成功');
			} else {
				api_return(2, '添加购物车失败');
			}
		} else {
			api_return(2, '商品不存在或已删除');
		}
	}

	/**
	 * 购物车列表
	 * */
	public function goodsCarList()
	{
		$input = I('post.');

		$uid = $input['uid'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$list = M('goods_car')->where(array('uid' => $uid))->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);
				$goods_info = M('goods')->where(array('id' => $v['goods_id']))->find();
				$v['goods_name'] = $goods_info['name'];
				$v['active'] = false;
			}

			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无数据');
		}
	}

	/**
	 * 移除购物车商品
	 * */
	public function removeGoodsCar()
	{
		$input = I('post.');
		$car_ids = $input['car_ids'];
		if (empty($car_ids)) api_return(2, '购物车ID缺失');
		$res = M('goods_car')->where(array('id' => array('IN', $car_ids)))->delete();
		if ($res) {
			api_return(1, '移除成功');
		} else {
			api_return(2, '移除失败');
		}
	}

	/**
	 * 购物车订单确认页
	 * */
	public function goodsCarOrderConfirm()
	{
		$input = I('post.');
		$uid = $input['uid'];
		$car_ids = $input['car_ids'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($car_ids)) api_return(2, '购物车ID缺失');

		$car_list = M('goods_car')->field('id,goods_id,img,spec,price,count')->where(array('id' => array('IN', $car_ids)))->select();
		$all_price = 0;
		if ($car_list) {
			foreach ($car_list as &$v) {
				$goods_name = getDbFieldValue('goods', array('id' => $v['goods_id']), 'name');
				$v['goods_name'] = $goods_name;
				$v['img'] = getPicture($v['img']);
				$v['spec'] = implode('；', json_decode($v['spec'], true));
				$all_price += sprintf("%.2f", $v['price'] * $v['count']);
			}
			//默认收货地址
			$address_info = M('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(array('uid' => $uid, 'is_default' => 1))->find();
			$address_info['province'] = getProvinceName($address_info['province_id']);
			$address_info['city'] = getCityName($address_info['city_id']);
			$address_info['area'] = getAreaName($address_info['area_id']);
			unset($address_info['province_id']);
			unset($address_info['city_id']);
			unset($address_info['area_id']);

			$pay_type_arr = array(
				array(
					'id' => 1,
					'name' => '微信支付'
				)
			);

			$send_type_arr = array(
				array(
					'id' => 1,
					'name' => '快递免邮'
				)
			);

			$data = array(
				'goods_list' => $car_list,
				'all_price' => $all_price,
				'address' => $address_info ? $address_info : array(),
				'pay_type_arr' => $pay_type_arr,
				'send_type_arr' => $send_type_arr
			);
			api_return(1, '获取数据成功', $data);
		} else {
			api_return(2, '购物车商品数据异常');
		}
	}

	/**
	 * 立即支付【生成待支付订单】 之后 发起支付
	 * */
	public function addGoodsCarOrder()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$car_ids = $input['car_ids'];
		$address_id = $input['address_id'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($car_ids)) api_return(2, '购物车ID缺失');
		if (empty($address_id)) api_return(2, '请选择收货地址');

		$user_info = getUserInfo($uid, 'openid');
		if (empty($user_info)) api_return(2, '用户信息不存在或已删除');

		$model = M();
		$model->startTrans();

		try {
			$car_list = M('goods_car')->field('id,goods_id,price,spec,count')->where(array('id' => array('IN', $car_ids)))->select();
			$all_price = 0;
			$order_res = false;
			$up_order_res = true;
			$goods_order = array();
			$order_ids = '';

			if ($car_list) {
				$address_info = M('address')->where(array('id' => $address_id))->find();
				//支付订单号
				$pay_order_sn = 'PAY' . date('Ymd') . rand(1000, 9999) . $uid;

				foreach ($car_list as $k => &$v) {
					$goods_info = M('goods')->field('id,name,supplier_id')->where(array('id' => $v['goods_id']))->find();

					$spec_info = M('goods_spec')->where(array('goods_id' => $v['goods_id'], 'spec' => $v['spec']))->find();
					if ($spec_info) {
						if ($v['count'] > $spec_info['count']) api_return(2, $goods_info['name'] . '库存不足');
					} else {
						api_return(2, $goods_info['name'] . '规格不存在或已删除');
					}

					$all_price += sprintf("%.2f", $v['price'] * $v['count']);

					$now_goods_price = $v['price'] * $v['count'];

					$wait_order_info = M('order')->where(array('pay_order_sn' => $pay_order_sn, 'supplier_id' => $goods_info['supplier_id']))->find();

					if ($wait_order_info) {
						$up_order_data = array(
							'all_price' => $now_goods_price + $wait_order_info['all_price'],
							'pay_price' => $now_goods_price + $wait_order_info['pay_price']
						);
						$up_order_res = $model->table('teach_order')->where(array('id' => $wait_order_info['id']))->save($up_order_data);

						if (!$up_order_res) break;

						$order_res = $wait_order_info['id'];
					} else {
						//订单主表添加数据
						$order_sn = 'SN' . date('Ymd') . rand(1000, 9999) . $uid;
						$iid = getDbFieldValue('ucenter_member', array('id' => $uid), 'iid');
						$order_data = array(
							'iid' => $iid ? $iid : 0,
							'uid' => $uid,
							'supplier_id' => $goods_info['supplier_id'],
							'order_sn' => $order_sn,
							'pay_order_sn' => $pay_order_sn,
							'all_price' => $now_goods_price,
							'pay_price' => $now_goods_price,
							'type' => 4,
							'get_username' => $address_info['username'],
							'get_mobile' => $address_info['mobile'],
							'get_province' => getProvinceName($address_info['province_id']),
							'get_city' => getCityName($address_info['city_id']),
							'get_area' => getAreaName($address_info['area_id']),
							'get_address' => $address_info['address'],
							'car_ids' => $car_ids,
							'share_uid' => getShareUid($uid),
							'create_time' => time()
						);
						$order_res = $model->table('teach_order')->add($order_data);
					}

					if ($order_res) {
						//当$order_res为数值时（订单ID），走该分支
						if ($order_ids == '') {
							$order_ids = $order_res;
						} else {
							$order_ids .= ',' . $order_res;
						}
					}

					if (!$order_res) break;

					//准备订单副表数据
					$goods_info = M('goods')->field('id,name,supplier_id')->where(array('id' => $v['goods_id']))->find();
					$spec_info = M('goods_spec')->where(array('goods_id' => $v['goods_id'], 'spec' => $v['spec']))->find();
					$goods_order[] = array(
						'order_id' => $order_res,
						'supplier_id' => $goods_info['supplier_id'],
						'to_id' => $v['goods_id'],
						'img' => $spec_info['img'],
						'name' => $goods_info['name'],
						'spec' => $spec_info['spec'],
						'old_price' => $spec_info['old_price'],
						'price' => $spec_info['price'],
						'count' => $v['count'],
						'create_time' => time()
					);
				}
				$vice_order_res = $model->table('teach_vice_order')->addAll($goods_order);

				if ($order_res && $vice_order_res && $up_order_res) {
					Vendor('pay.pay');
					$data = array(
//						'amount' => floatval($all_price) * 100,
						'amount' => floatval(0.05) * 100,
						'body' => '商品支付',
						'description' => '商品支付',
						'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/goodsNotice',
						'out_trade_no' => $pay_order_sn,
						'product' => 'WECHAT_LITE',
						'subject' => '商品支付'
					);
					$appid = C('XCX_APPID');
					$openid = $user_info['openid'];
					$obj = new \pay($data, $appid, $openid);

					$recceivers = array();
					foreach (explode(',', $order_ids) as &$v) {
						$recceivers[] = json_decode(getRecceivers($v), true);
					}
					$recceivers = getRecceivers($v);
					$recceivers = json_encode(array_merge(array_unique($recceivers, SORT_REGULAR)));

					$result = $obj->xcxPay($recceivers);
					if ($result['result'] != 1) api_return(2, $result['message']);

					$return_data = array(
						'pay_data' => $result['data'],
						'order_id' => $order_ids
					);

					$model->commit();
					api_return(1, '获取数据成功', $return_data);
				} else {
					$model->rollback();
					api_return(2, '订单生成失败');
				}
			} else {
				$model->rollback();
				api_return(2, '购物车商品数据异常');
			}
		} catch (\Exception $e) {
			api_return(2, '系统繁忙，请稍后再试' . $e);
		}
	}

	/**
	 * 题库首页数据
	 * */
	public function questionIndex()
	{
		$input = I('post.');

		$sid = $input['sid'] ? $input['sid'] : 0;
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		//学科
		$subject_list = M('subject')->field('id,name')->order('sort asc')->select();

		if (empty($sid)) $sid = $subject_list[0]['id'];
		$one_chapter_list = M('chapter')->field('id')->where(array('sid' => $sid, 'pid' => 0))->select();
		if ($one_chapter_list) {
			$one_chapter_ids = implode(',', array_column($one_chapter_list, 'id'));
			$where['one_chapter_id'] = array('IN', $one_chapter_ids);
			$hot_practice_list = M('practice')->field('id,name,single_count,check_count,tags,write_count')->where(array('type' => 2, 'is_hot' => 1))->where($where)->order('sort asc')->page($page, $pagesize)->select();
			//热门试卷
			if ($hot_practice_list) {
				foreach ($hot_practice_list as &$v) {
					$v['single_count'] = intval($v['single_count']);
					$v['check_count'] = intval($v['check_count']);

					$v['tags'] = $v['tags'] ? explode(',', $v['tags']) : array();
				}
			}
		} else {
			$hot_practice_list = array();
		}

		$data = array(
			'subject_list' => $subject_list,
			'hot_practice_list' => $hot_practice_list
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 章节目录
	 * */
	public function chapterList()
	{
		$input = I('post.');

		$sid = $input['sid'];

		$empty_son_list = array(
			array(
				'id' => 0,
				'name' => '选择知识点',
			)
		);
		$empty_list = array(
			array(
				'id' => 0,
				'name' => '选择章节',
				'son_list' => $empty_son_list
			)
		);
		$list = M('chapter')->field('id,name')->where(array('sid' => $sid, 'pid' => 0))->order('sort asc')->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['radio_check'] = false;
				$son_list = M('chapter')->field('id,name')->where(array('pid' => $v['id']))->order('sort asc')->select();
				if ($son_list) {
					foreach ($son_list as &$val) {
						$val['radio_check'] = false;
					}
				}
				$v['son_list'] = $son_list ? array_merge($empty_son_list, $son_list) : $empty_son_list;
			}
			api_return(1, '获取数据成功', $list ? array_merge($empty_list, $list) : $empty_list);
		} else {
			api_return(1, '获取数据成功', $empty_list);
		}
	}

	/**
	 * 练习册/试卷 列表
	 * */
	public function practiceList()
	{
		$input = I('post.');

		$sid = $input['sid'];
		$style = $input['style'] ? $input['style'] : 1;//1：章节练习，2：巩固考试，3：真题模考，4：精品试卷

		//章节练习筛选条件
		$two_chapter_ids = $input['two_chapter_ids'] ? $input['two_chapter_ids'] : '';
		//巩固考试筛选条件
		$one_chapter_id = $input['one_chapter_id'] ? $input['one_chapter_id'] : 0;
		$two_chapter_id = $input['two_chapter_id'] ? $input['two_chapter_id'] : 0;
		//真题模考筛选条件
		$search_value = $input['search_value'] ? $input['search_value'] : '';//关键词或者年份

		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($sid)) api_return(2, '学科ID缺失');

		$where['sid'] = $sid;
		$where['style'] = $style;

		if ($two_chapter_ids) $where['two_chapter_id'] = array('IN', $two_chapter_ids);
		if ($one_chapter_id) $where['one_chapter_id'] = $one_chapter_id;
		if ($two_chapter_id) $where['two_chapter_id'] = $two_chapter_id;
		if ($search_value) {
			$condition['name'] = array('LIKE', '%' . $search_value . '%');
			$condition['year'] = $search_value;
			$condition['_logic'] = 'OR';
			$where[] = $condition;
		}
		$list = M('practice')->field('id,year,name,single_count,check_count,true_rate,write_count,tags')->where($where)->order('sort asc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['name'] = $v['year'] . $v['name'];
				$v['single_count'] = intval($v['single_count']);
				$v['check_count'] = intval($v['check_count']);
				$v['tags'] = $v['tags'] ? explode(',', $v['tags']) : array();
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 试卷介绍
	 * */
	public function practiceInfo()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '试卷ID缺失');

		$info = M('practice')->field('id,year,name,single_count,check_count,score,desc')->where(array('id' => $id))->find();
		if ($info) {
			$info['single_count'] = intval($info['single_count']);
			$info['check_count'] = intval($info['check_count']);

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '试卷不存在或已删除');
		}
	}

	/**
	 * 练习习题列表
	 * */
	public function exercisesList()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'] ? $input['uid'] : 0;

		if (empty($id)) api_return(2, '练习册ID缺失');

		$info = M('practice')->where(array('id' => $id))->find();
		$title = $info['year'] . $info['name'];
		$tags = $info['tags'] ? explode(',', $info['tags']) : array();

		$list = M('practice_exercises pe')->join('teach_exercises e ON pe.exercises_id = e.id')->field('pe.id,e.question,e.analysis,e.style,e.option')->where(array('pe.practice_id' => $id))->order('pe.sort asc')->select();
		if ($list) {
			foreach ($list as $key => &$v) {
				$v['list_index'] = $key + 1;
				$v['look_answer'] = false;
				$option = json_decode($v['option'], true);

				$true_answer = '';
				foreach ($option as $val) {
					if ($val['answer']) {
						if ($true_answer == '') {
							$true_answer = $val['key'];
						} else {
							$true_answer .= ',' . $val['key'];
						}
					}
					$v['true_answer'] = $true_answer;
				}
				$v['option'] = $option;
			}
		} else {
			$list = array();
		}

		//查询 练习册/试卷 是否收藏
		if ($uid) {
			$is_collect = M('collect')->where(array('uid' => $uid, 'to_id' => $id, 'type' => 3, 'is_collect' => 1))->count();
		} else {
			$is_collect = 0;
		}

		$data = array(
			'title' => $title ? $title : '',
			'tags' => $tags,
			'is_collect' => $is_collect,
			'list' => $list
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 智能组题
	 * */
	public function wisdomMakeExercises()
	{
		$input = I('post.');

		$two_chapter_ids = $input['two_chapter_ids'];
		$title = $input['title'];
		$count = $input['count'];
		$single_score = $input['single_score'];

		if (empty($two_chapter_ids)) api_return(2, '请选择知识点');
		if (empty($title)) api_return(2, '请输入试卷名称');
		if (empty($count)) api_return(2, '请输入题目数量');
		if (empty($single_score)) api_return(2, '请输入每题分数');

		$list = M('exercises')->field('id,question,analysis,style,option,RAND() r')->where(array('two_chapter_id' => array('IN', $two_chapter_ids)))->order('r asc')->limit($count)->select();
		$single_count = 0;
		$check_count = 0;
		if ($list) {
			foreach ($list as $key => &$v) {
				if ($v['style'] == 1) {
					++$single_count;
				} else {
					++$check_count;
				}

				$v['list_index'] = $key + 1;
				$v['look_answer'] = false;
				$option = json_decode($v['option'], true);

				$true_answer = '';
				foreach ($option as $val) {
					if ($val['answer']) {
						if ($true_answer == '') {
							$true_answer = $val['key'];
						} else {
							$true_answer .= ',' . $val['key'];
						}
					}
					$v['true_answer'] = $true_answer;
				}
				$v['option'] = $option;
			}
			$data = array(
				'title' => $title,
				'score' => count($list) * $single_score,
				'single_count' => $single_count,
				'check_count' => $check_count,
				'tags' => array(),
				'is_collect' => 0,
				'list' => $list
			);

			api_return(1, '获取数据成功', $data);
		} else {
			api_return(2, '所选章节未查询到题目，生成试卷失败');
		}
	}

	/**
	 * 保存做题结果
	 * */
	public function saveExercisesResult()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$practice_id = $input['practice_id'];
		$single_count = $input['single_count'];
		$single_true_count = $input['single_true_count'];
		$single_true_rate = $input['single_true_rate'];
		$check_count = $input['check_count'];
		$check_true_count = $input['check_true_count'];
		$check_true_rate = $input['check_true_rate'];
		$all_rate = $input['all_rate'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($practice_id)) api_return(2, 'ID缺失');

		$info = M('practice')->field('single_score,check_score')->where(array('id' => $practice_id))->find();
		if (empty($info)) api_return(2, '系统繁忙，请稍后再试');

		$score = $info['single_score'] * $single_true_count + $info['check_score'] * $check_true_count;

		$practice_info = M('practice')->where(array('id' => $practice_id))->find();
		//试卷总分数
		$all_score = $practice_info['single_count'] * $practice_info['single_score'] + $practice_info['check_count'] * $practice_info['check_score'];
		$is_pass = ($all_score * 0.6 <= $score) ? 1 : 0;

		$data = array(
			'uid' => $uid,
			'practice_id' => $practice_id,
			'single_count' => $single_count,
			'single_true_count' => $single_true_count,
			'single_true_rate' => $single_true_rate,
			'check_count' => $check_count,
			'check_true_count' => $check_true_count,
			'check_true_rate' => $check_true_rate,
			'all_rate' => $all_rate,
			'score' => $score,
			'is_pass' => $is_pass,
			'create_time' => time()
		);
		$res = M('user_test_log')->add($data);
		if ($res) {
			$getPracticeTrueRate = getPracticeTrueRate($practice_id);
			M('practice')->where(array('id' => $practice_id))->save(array('true_rate' => $getPracticeTrueRate['all_rate_avg'], 'write_count' => $getPracticeTrueRate['write_count'], 'update_time' => time()));

			api_return(1, '保存结果成功');
		} else {
			api_return(2, '保存结果失败');
		}
	}

	/**
	 * 高频数据集合
	 * */
	public function errorLevelData()
	{
		$input = I('post.');

		$sid = $input['sid'];

		if (empty($sid)) api_return(2, '学科ID缺失');

		$one_error_level = M('exercises')->where(array('sid' => $sid, 'error_level' => 1))->count();
		$two_error_level = M('exercises')->where(array('sid' => $sid, 'error_level' => 2))->count();
		$three_error_level = M('exercises')->where(array('sid' => $sid, 'error_level' => 3))->count();

		$data = array(
			'one_error_level' => $one_error_level > 100 ? 100 : $one_error_level,
			'two_error_level' => $two_error_level > 100 ? 100 : $two_error_level,
			'three_error_level' => $three_error_level > 100 ? 100 : $three_error_level
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 高频数据习题列表
	 * */
	public function errorLevelExercisesList()
	{
		$input = I('post.');

		$sid = $input['sid'];
		$error_level = $input['error_level'];

		if (empty($sid)) api_return(2, '学科ID缺失');

		$list = M('exercises')->field('id,question,analysis,style,option')->where(array('sid' => $sid, 'error_level' => $error_level))->limit(100)->select();
		if ($list) {
			foreach ($list as $key => &$v) {
				$v['list_index'] = $key + 1;
				$v['look_answer'] = false;
				$option = json_decode($v['option'], true);

				$true_answer = '';
				foreach ($option as $val) {
					if ($val['answer']) {
						if ($true_answer == '') {
							$true_answer = $val['key'];
						} else {
							$true_answer .= ',' . $val['key'];
						}
					}
					$v['true_answer'] = $true_answer;
				}
				$v['option'] = $option;
			}

			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无数据');
		}
	}

	/**
	 * 用户错题处理
	 * */
	public function doUserErrorExercises()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$sid = $input['sid'];
		$title = $input['title'];
		$answer_ids = $input['answer_ids'];//本次做的题目id集合
		$error_answer_list = $input['error_answer_list'];
		$is_exercises_id = $input['is_exercises_id'] ? $input['is_exercises_id'] : 0;//$error_answer_list中的id是否是exercises_id；0：否，1：是（智能练习，高频数据的值为1）

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($sid)) api_return(2, '学科ID缺失');

		//将本次做过的题目在错题表中全部删除
		$exercises_ids_list = M('practice_exercises')->field('exercises_id')->where(array('id' => array('IN', $answer_ids)))->select();
		$exercises_ids = array_column($exercises_ids_list, 'exercises_id');
		if ($exercises_ids) M('user_error_exercises')->where(array('uid' => $uid, 'exercises_id' => array('IN', $exercises_ids)))->delete();

		if ($error_answer_list) {
			$data = array();
			$time = time();
			foreach (json_decode($error_answer_list, true) as &$v) {
				if ($is_exercises_id) {
					$exercises_info = M('exercises')->field('id,question,option,analysis')->where(array('id' => $v['id']))->find();
				} else {
					$exercises_info = M('practice_exercises pe')->join('teach_exercises e ON pe.exercises_id = e.id')->field('e.id,e.question,e.option,e.analysis')->where(array('pe.id' => $v['id']))->find();
				}
				if ($exercises_info) {
					$option = json_decode($exercises_info['option'], true);
					if ($option) {
						foreach ($option as &$val) {
							if (strlen($v['you_answer']) > 1) {
								foreach (explode(',', $v['you_answer']) as $value) {
									if ($value == $val['key']) {
										$val['is_choose'] = true;
									}
								}
							} else {
								if ($v['you_answer'] == $val['key']) {
									$val['is_choose'] = true;
								}
							}
						}

						//新增错题
						$data[] = array(
							'uid' => $uid,
							'sid' => $sid,
							'title' => $title,
							'exercises_id' => $exercises_info['id'],
							'question' => $exercises_info['question'],
							'option' => json_encode($option),
							'analysis' => $exercises_info['analysis'],
							'create_time' => $time
						);
					}
				}
			}
			if ($data) M('user_error_exercises')->addAll($data);
		}
	}

	/**
	 * 题目做题处理
	 * */
	public function doExercisesLog()
	{
		$input = I('post.');

		$question_list = json_decode($input['question_list'], true);

		if ($question_list) {
			$add_data = array();
			$exercises_all_log_data = array();
			$time = time();
			foreach ($question_list as &$v) {
				$exercises_id = M('practice_exercises')->where(array('id' => $v['id']))->getField('exercises_id');
				if ($exercises_id) {
					$exercises_question = M('exercises')->where(array('id' => $exercises_id))->getField('question');
					if ($v['you_answer'] && $exercises_question) {
						$exercises_all_log_data[] = array(
							'exercises_id' => $exercises_id,
							'question' => $exercises_question,
							'is_true' => $v['is_true'] ? 1 : 0,
							'create_time' => $time
						);
					}

					$info = M('exercises_log')->where(array('exercises_id' => $exercises_id))->find();
					if ($info) {
						$do_count = $info['do_count'] + 1;
						$true_count = $v['is_true'] ? $info['true_count'] + 1 : $info['true_count'];
						$true_rate = sprintf("%.2f", $true_count / $do_count * 100);
						$error_count = !$v['is_true'] ? $info['error_count'] + 1 : $info['error_count'];
						$error_rate = sprintf("%.2f", $error_count / $do_count * 100);

						$up_data = array(
							'do_count' => $do_count,
							'true_count' => $true_count,
							'true_rate' => $true_rate,
							'error_count' => $error_count,
							'error_rate' => $error_rate,
							'update_time' => time()
						);
						M('exercises_log')->where(array('exercises_id' => $exercises_id))->save($up_data);
					} else {
						$add_data[] = array(
							'exercises_id' => $exercises_id,
							'do_count' => 1,
							'true_count' => $v['is_true'] ? 1 : 0,
							'true_rate' => $v['is_true'] ? 100 : 0,
							'error_count' => !$v['is_true'] ? 1 : 0,
							'error_rate' => !$v['is_true'] ? 100 : 0,
							'update_time' => time()
						);
					}
				}
			}
			if ($exercises_all_log_data) {
				M('exercises_all_log')->addAll($exercises_all_log_data);
			}
			if ($add_data) {
				M('exercises_log')->addAll($add_data);
			}
		}
	}

	/**
	 * 我的错题
	 * */
	public function userErrorExercisesList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$sid = $input['sid'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($sid)) api_return(2, '学科ID缺失');

		$list = M('user_error_exercises')->field('id,title,question,option,analysis')->where(array('uid' => $uid, 'sid' => $sid))->order('create_time desc, id desc')->limit(100)->select();
		if ($list) {
			foreach ($list as &$v) {
				$option = json_decode($v['option'], true);
				$v['option'] = $option;
				$answer_count = 0;
				foreach ($option as &$value) {
					if ($value['answer']) {
						$answer_count = $answer_count + 1;
					}
				}
				if ($answer_count > 1) {
					$v['style'] = 2;
				} else {
					$v['style'] = 1;
				}
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无数据');
		}
	}

	/**
	 * 试卷收藏列表
	 * */
	public function practiceCollectList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$sid = $input['sid'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($sid)) api_return(2, '学科ID缺失');

		$list = M('collect c')->join('teach_practice p ON c.to_id = p.id')->field('p.id,p.year,p.name,p.single_count,p.check_count,p.write_count,p.tags')->where(array('c.uid' => $uid, 'c.sid' => $sid, 'c.type' => 3, 'c.is_collect' => 1))->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['single_count'] = intval($v['single_count']);
				$v['check_count'] = intval($v['check_count']);
				$v['name'] = $v['year'] . $v['name'];
				$v['tags'] = $v['tags'] ? explode(',', $v['tags']) : array();
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 直播专区
	 * */
	public function liveList()
	{
		$input = I('post.');

		$iid = $input['iid'];
		$uid = $input['uid'];
		$date = $input['date'];//0：全部，非0为日期
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($iid)) api_return(2, '机构ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$live_where['iid'] = $iid;
		$live_where['audit_status'] = 1;
		$live_where['status'] = 1;
		$live_where['is_activity'] = 0;
		$live_where['is_del'] = 0;
		$live_where['live_time'] = array('egt', time());

		if ($date != 0) $live_where['live_time_date'] = $date;

		$list = M('live_course')->field('id,name,img,price,live_time,teacher_id,status,is_activity')->where($live_where)->order('id desc')->page($page, $pagesize)->select();
		file_put_contents(RUNTIME_PATH . 'sql.txt', M()->getLastSql());
		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);
				$v['live_time'] = time_format($v['live_time'], 'H:i');

				//查询老师信息
				$teacher_info = M('teacher')->field('id,name,avatar_id,tag')->where(array('id' => $v['teacher_id']))->find();
				$v['teacher_name'] = $teacher_info['name'];
				$v['teacher_avatar'] = doAvatar($teacher_info['avatar_id']);
				$v['teacher_tag'] = $teacher_info['tag'];

				//查询是否报名；大于0则表示已报名
				if ($uid) {
					$is_enlist = M('order o')->join('teach_vice_order vo ON o.id = vo.order_id')->where(array('o.uid' => $uid, 'o.type' => 1, 'o.is_pay' => 1, 'vo.to_id' => $v['id']))->count();
				} else {
					$is_enlist = 0;
				}
				$v['is_enlist'] = $is_enlist;
			}
		} else {
			$list = array();
		}
		if ($page == 1) {
			$time_list = getListTimeList();
		} else {
			$time_list = array();
		}

		$data = array(
			'list' => $list,
			'time_list' => $time_list
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 直播课详情【未报名】
	 * */
	public function liveDetail()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$share_uid = $input['share_uid'] ? $input['share_uid'] : 0;

		if (empty($id)) api_return(2, '直播课ID缺失');

		$info = M('live_course')->field('id,name,live_time,live_time_slot,price,enlist_count,img,teacher_id,desc,status,is_activity')->where(array('id' => $id))->find();
		if ($info) {
			$info['price'] = getCoursePrice($info['id'], 3, $info['price'], $info['is_activity']);

			if ($uid) {
				$is_buy = M('order o')->join('teach_vice_order vo ON o.id = vo.order_id')->where(array('o.uid' => $uid, 'o.type' => 1, 'o.is_pay' => 1, 'vo.to_id' => $id))->count();
				if ($is_buy > 0 || $info['status'] == 3) {
					$info['show_buy_btn'] = false;
				} else {
					$info['show_buy_btn'] = true;
				}
			} else {
				$info['show_buy_btn'] = true;
			}

			$info['live_time'] = time_format($info['live_time'], 'm月d日');
			$info['img'] = getPicture($info['img']);
			$info['desc'] = str_replace('<img src="', '<img style="width: 100%; height: auto" src="' . getHost(), $info['desc']);

			//查询老师信息
			$teacher_info = M('teacher')->field('id,name,avatar_id,desc')->where(array('id' => $info['teacher_id']))->find();
			$info['teacher_name'] = $teacher_info['name'];
			$info['teacher_avatar'] = doAvatar($teacher_info['avatar_id']);
			$info['teacher_desc'] = $teacher_info['desc'];

			//获取活动数据
			$activity_course_info = getActivityCourseInfo($id, 3, $info['price'], $info['is_activity']);
			$info['group_len'] = count($activity_course_info['group_list']);
			$info['group_list'] = $activity_course_info['group_list'];
			$info['all_group_people'] = $activity_course_info['all_group_people'];
			$info['price'] = $activity_course_info['price'];

			//按钮控制；1：立即购买，2：发起拼团，3：参与拼团，4：立即秒杀，5：不显示按钮
			$user_live_count = M('order o')->join('teach_vice_order vc ON o.id = vc.order_id')->where(array('o.uid' => $uid, 'o.type' => 1, 'o.is_pay' => 1, 'vc.to_id' => $id))->count();
			if ($user_live_count > 0) {
				//严格控制用户之前购买直播课程的情况下不能再次购买
				$info['btn'] = 5;
				$info['btn_name'] = '';
			} else {
				if ($info['is_activity'] == 0) {
					//无活动
					$info['btn'] = 1;
					$info['btn_name'] = '立即购买';
				} else if ($info['is_activity'] == 1) {
					//团购活动
					$work_info = M('group_work')->where(array('course_id' => $id, 'category' => 3, 'status' => 1))->find();
					if ($work_info) {
						$info['group_price'] = $work_info['group_price'];
						$info['chief_price'] = $work_info['chief_price'];

						//团ID，供底部参与拼团按钮使用
						if ($share_uid > 0) {
							$chief_group_join_info = M('group_join')->where(array('uid' => $share_uid, 'gid' => $work_info['id']))->find();
							$group_join_pid = $chief_group_join_info['is_chief'] == 1 ? $chief_group_join_info['id'] : $chief_group_join_info['pid'];
							$info['group_join_pid'] = $group_join_pid ? $group_join_pid : 0;

							//隐藏底部【参与拼团】按钮，原因，用户分享的这个团人数满了
							if ($chief_group_join_info['status'] == 2) $info['hide_btn'] = true;
						}
					}

					$join_count = M('group_join')->where(array('gid' => $work_info['id'], 'uid' => $uid, 'status' => array('IN', '1,2')))->count();
					if ($join_count == 0) {
						//团个数
						$chief_count = M('group_join')->where(array('gid' => $work_info['id'], 'pid' => 0, 'status' => array('IN', '1,2')))->count();
						if ($chief_count >= $work_info['group_limit_number'] && $chief_count > 0) {
							$info['btn'] = 3;
							$info['btn_name'] = '参与拼团';
						} else {
							if ($share_uid > 0) {
								//查询分享者是否在团中
								$share_join_count = M('group_join')->where(array('gid' => $work_info['id'], 'uid' => $share_uid, 'status' => array('IN', '1,2')))->count();
								if ($share_join_count > 0) {
									$info['btn'] = 3;
									$info['btn_name'] = '参与拼团';
								} else {
									$info['btn'] = 2;
									$info['btn_name'] = '发起拼团';
								}
							} else {
								$info['btn'] = 2;
								$info['btn_name'] = '发起拼团';
							}
						}
					} else {
						$info['btn'] = 5;
						$info['btn_name'] = '';
					}
				} else {
					//秒杀活动
					if ($user_live_count > 0) {
						$info['btn'] = 5;
						$info['btn_name'] = '';
					} else {
						//秒杀活动
						$info['btn'] = 4;
						$info['btn_name'] = '立即秒杀';
					}
				}
			}

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '直播课不存在或已删除');
		}
	}

	public function getLiveSig()
	{
		$input = I('post.');

		$user_id = $input['user_id'];

		$userSig = getUserSig($user_id);

		api_return(1, '获取数据成功', $userSig);
	}

	/**
	 * 老师详情
	 * */
	public function teacherDetail()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];

		if (empty($id)) api_return(2, '老师ID缺失');

		$info = M('teacher')->field('id,name,avatar_id,tag,sign,desc')->where(array('id' => $id))->find();

		//相关课程列表
		if ($info) {
			$info['avatar'] = doAvatar($info['avatar_id']);

			$live_list = M('live_course')->field('id,name,price,img,status')->where(array('teacher_id' => $id, 'is_del' => 0, 'audit_status' => 1))->order('create_time desc')->select();
			if ($live_list) {
				//查询是否报名；大于0则表示已报名
				foreach ($live_list as &$v) {
					$v['img'] = getPicture($v['img']);
					$is_buy = M('order o')->join('teach_vice_order vo ON o.id = vo.order_id')->where(array('o.uid' => $uid, 'o.type' => 1, 'o.is_pay' => 1, 'vo.to_id' => $v['id']))->count();

					$v['is_buy'] = $is_buy;
					if ($is_buy > 0 || $v['status'] == 3) {
						$v['show_buy_btn'] = false;
					} else {
						$v['show_buy_btn'] = true;
					}
				}
			} else {
				$live_list = array();
			}
			$info['live_list'] = $live_list;

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '老师信息不存在或已删除');
		}
	}

	/**
	 * 直播报名详情
	 * */
	public function liveEnlistInfo()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$is_chief = $input['is_chief'] ? $input['is_chief'] : 0;//1：团长，2：团员

		if (empty($id)) api_return(2, '直播ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('live_course')->field('id,name,img,price,live_time,teacher_id,is_activity')->where(array('id' => $id))->find();
		if ($info) {
			$info['price'] = getCoursePrice($info['id'], 3, $info['price'], $info['is_activity']);

			$info['img'] = getPicture($info['img']);
			$info['live_time'] = time_format($info['live_time'], 'H:i');

			//查询老师信息
			$teacher_info = M('teacher')->field('id,name,avatar_id,tag')->where(array('id' => $info['teacher_id']))->find();
			$info['teacher_name'] = $teacher_info['name'];
			$info['teacher_avatar'] = doAvatar($teacher_info['avatar_id']);
			$info['teacher_tag'] = $teacher_info['tag'];

			//优惠券列表
			$empty_coupon_list = array(
				array(
					'id' => 0,
					'name' => '请选择优惠券',
					'deduct_price' => 0
				)
			);
			$user_coupon_list = getUserCoupon($uid, $info['price'], 3);
			$info['user_coupon_list'] = $user_coupon_list ? array_merge($empty_coupon_list, $user_coupon_list) : $empty_coupon_list;

			$pay_type_arr = array(
				array(
					'id' => 1,
					'name' => '微信支付'
				)
			);
			$info['pay_type_arr'] = $pay_type_arr;

			if ($info['is_activity'] > 0) $info['price'] = getCoursePrice($info['id'], 3, $info['price'], $info['is_activity'], $is_chief);

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '直播课不存在或已删除');
		}
	}

	/**
	 * 直播课程立即支付
	 * */
	public function payLiveCourse()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$is_chief = $input['is_chief'] ? $input['is_chief'] : 0;
		$pid = $input['pid'] ? $input['pid'] : 0;
		$user_coupon_id = $input['user_coupon_id'] ? $input['user_coupon_id'] : 0;

		if (empty($id)) api_return(2, '直播课程ID缺失');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('live_course')->where(array('id' => $id))->find();
		if ($info) {
			$model = M();
			$model->startTrans();

			try {
				$order_sn = 'LIVE' . date('Ymd') . rand(1000, 9999) . $uid;
				$user_info = $model->table('teach_ucenter_member')->field('iid,share_uid,openid')->where(array('id' => $uid))->find();

				if ($user_coupon_id) {
					$coupon_info = $model->table('teach_user_coupon uc')->join('teach_coupon c ON uc.cid = c.id')->field('c.id,c.deduct_price')->where(array('uc.id' => $user_coupon_id))->find();
					$pay_price = $info['price'] - $coupon_info['deduct_price'];
				} else {
					$pay_price = $info['price'];
				}

				//生成待支付订单
				$data = array(
					'iid' => $user_info['iid'],
					'uid' => $uid,
					'order_sn' => $order_sn,
					'pay_order_sn' => $order_sn,
					'all_price' => $info['price'],
					'pay_price' => $pay_price,
					'user_coupon_id' => $user_coupon_id,
					'type' => 1,
					'share_uid' => $user_info['share_uid'] ? $user_info['share_uid'] : 0,
					'create_time' => time()
				);
				$order_id = $model->table('teach_order')->add($data);

				$vice_data = array(
					'order_id' => $order_id,
					'to_id' => $id,
					'img' => $info['img'],
					'name' => $info['name'],
					'live_open_time' => $info['live_time'],
					'price' => $info['price'],
					'count' => 1,
					'style' => $info['is_activity'],
					'create_time' => time()
				);
				$vice_res = $model->table('teach_vice_order')->add($vice_data);

				$surplus_res = true;
				$add_skill_res = true;
				$up_order = true;
				$group_join_res = true;
				if ($info['is_activity'] == 2) {
					//秒杀
					$skill_id = M('seckill')->where(array('category' => 3, 'course_id' => $id, 'status' => 1))->getField('id');

					$skill_data = array(
						'uid' => $uid,
						'category' => $info['is_activity'],
						'course_id' => $id,
						'seckill_id' => $skill_id
					);
					$skill_log_info = $model->table('teach_seckill_log')->where($skill_data)->find();

					//删除无效订单
					if ($skill_log_info && $skill_log_info['status'] == 0) {
						$del_order_id = getDbFieldValue('order', array('skill_log_id' => $skill_log_info['id']), 'id');

						//删除无效的秒杀记录
						$model->table('teach_seckill_log')->where($skill_data)->delete();
						//删除无效的订单
						$model->table('teach_order')->where(array('id' => $del_order_id))->delete();
						$model->table('teach_vice_order')->where(array('order_id' => $del_order_id))->delete();

						$model->table('teach_seckill')->where(array('id' => $skill_id))->setInc('surplus_count');
					}

					$add_skill_res = $model->table('teach_seckill_log')->add($skill_data);

					$up_order = $model->table('teach_order')->where(array('id' => $order_id))->setField('skill_log_id', $add_skill_res);

					//扣秒杀库存
					$surplus_res = $model->table('teach_seckill')->lock(true)->where(array('id' => $skill_id))->setDec('surplus_count');
				} else if ($info['is_activity'] == 1) {
					//团购
					$work_info = M('group_work')->where(array('course_id' => $id, 'category' => 3, 'status' => 1))->find();
					if ($work_info) {
						//删除无效拼团
						M('group_join')->where(array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0))->find();

						$join_id = getDbFieldValue('group_join', array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0), 'id');
						if ($join_id) {
							$del_order_id = getDbFieldValue('order', array('group_join_id' => $join_id), 'id');

							M('group_join')->where(array('uid' => $uid, 'gid' => $work_info['id'], 'status' => 0))->delete();
							//删除无效拼团产生的订单
							if ($join_id) M('order')->where(array('group_join_id' => $join_id))->delete();
							if ($del_order_id) M('vice_order')->where(array('order_id' => $del_order_id))->delete();
						}

						$group_join_data = array(
							'uid' => $uid,
							'pid' => $pid,
							'gid' => $work_info['id'],
							'is_chief' => $is_chief,
							'create_time' => time()
						);
						//新增参团数据
						$group_join_res = $model->table('teach_group_join')->add($group_join_data);
						//修改订单表参团id关联
						$up_order = $model->table('teach_order')->where(array('id' => $order_id))->setField('group_join_id', $group_join_res);

						if ($is_chief == 1) {
							//发起拼团，添加redis集合，到了拼团结束时间就自动执行相关程序
							$redisCtr = A('Home/Redis');
							$task_param = array(
								'group_join_id' => $group_join_res,
								'category' => 3,
								'course_id' => $id
							);
							//添加结束执行的redis记录到集合
							$redisCtr->addRedis('groupChiefEnd', time() + $work_info['time_limit'] * 60, $task_param);
						}
					}
				}

				Vendor('pay.pay');
				$data = array(
					'amount' => floatval(0.01) * 100,
//					'amount' => $pay_price,
					'body' => '直播课程支付',
					'description' => '直播课程支付',
					'notify_url' => 'https://yuezhang.yue688.cn/index.php/Home/XcxPayNotice/liveNotice',
					'out_trade_no' => $order_sn,
					'channel' => 'WECHAT',
					'product' => 'WECHAT_LITE',
					'subject' => $info['name']
				);
				$appid = C('XCX_APPID');
				$obj = new \pay($data, $appid, $user_info['openid']);

				$receivers = getRecceivers($order_id);
				$pay_info = $obj->xcxPay($receivers);

				if ($order_id && $vice_res && $surplus_res && $add_skill_res && $up_order && $group_join_res) {
					$model->commit();
					api_return(1, '生成待支付订单成功', $pay_info['data']);
				} else {
					$model->rollback();
					api_return(2, '生成订单失败');
				}
			} catch (\Exception $e) {
				api_return(2, '系统繁忙，请稍后再试~');
			}
		} else {
			if (empty($uid)) api_return(2, '直播课程不存在或已删除');
		}
	}

	/**
	 * 签到信息
	 * */
	public function signInfo()
	{
		$input = I('post.');

		$iid = $input['iid'];
		$uid = $input['uid'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($iid)) api_return(2, '请先绑定机构');
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		//已连续签到天数
		$continuity_day = M('sign_log')->where(array('uid' => $uid, 'date' => array('egt', date('Y-m-d', strtotime('-1 day')))))->order('date desc')->getField('continuity_day');
		$continuity_day = addZero($continuity_day ? $continuity_day : 0);

		//再连续签到多少天可获取优惠券
		$get_day = M('coupon')->where(array('iid' => $iid, 'get_day' => array('gt', $continuity_day)))->order('get_day asc')->getField('get_day');
		if ($get_day > 0) {
			$need_day = $get_day - $continuity_day;
		} else {
			$need_day = 0;
		}

		//今日是否签到
		$is_sign = M('sign_log')->where(array('uid' => $uid, 'date' => array('egt', date('Y-m-d'))))->count();

		//签到记录
		$list = M('sign_log')->field('id,date,desc')->where(array('uid' => $uid))->order('date desc')->page($page, $pagesize)->select();

		$data = array(
			'continuity_day' => $continuity_day,
			'need_day' => $need_day,
			'is_sign' => $is_sign,
			'list' => $list ? $list : array()
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 签到
	 * */
	public function sign()
	{
		$input = I('post.');

		$uid = $input['uid'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		//机构id
		$iid = getDbFieldValue('ucenter_member', array('id' => $uid), 'iid');
		if (empty($iid)) api_return(2, '您还未绑定机构，签到失败');

		//今天
		$date = date('Y-m-d');
		$count = M('sign_log')->where(array('uid' => $uid, 'date' => $date))->count();
		//昨天
		$yesterday = date("Y-m-d", strtotime("-1 day"));
		$yesterday_info = M('sign_log')->where(array('uid' => $uid, 'date' => $yesterday))->find();
		if ($yesterday_info) {
			$continuity_day = $yesterday_info['continuity_day'] + 1;
		} else {
			$continuity_day = 1;
		}
		$Model = M();
		$Model->startTrans();
		try {
			if ($count == 0) {
				$coupon_list = $Model->table('teach_coupon')->field('id,get_count,use_day')->where(array('iid' => $iid, 'get_day' => $continuity_day, 'status' => 0, 'is_del' => 0))->select();
				if ($coupon_list) {
					$user_sign_status = true;
					$user_coupon_data = array();
					foreach ($coupon_list as &$v) {
						//用户领取该优惠券次数
						$user_get_count = $Model->table('teach_user_coupon')->where(array('uid' => $uid, 'cid' => $v['id']))->count();
						if ($v['get_count'] > $user_get_count) {
							$user_coupon_data[] = array(
								'iid' => $iid,
								'uid' => $uid,
								'cid' => $v['id'],
								'expire_time' => time() + $v['use_day'] * 3600 * 24,
								'create_time' => time()
							);
						}
					}
					if ($user_coupon_data) {
						$user_coupon_res = $Model->table('teach_user_coupon')->addAll($user_coupon_data);
						if ($user_coupon_res) {
							$user_sign_status = true;
						} else {
							$user_sign_status = false;
						}
					} else {
						$user_coupon_res = true;
						$user_sign_status = false;
					}
				} else {
					$user_coupon_res = true;
				}
				if ($user_sign_status) {
					$desc = '连续签到' . $continuity_day . '天，获得优惠券';
				} else {
					$desc = '已签到' . $continuity_day . '天';
				}
				$data = array(
					'iid' => $iid,
					'uid' => $uid,
					'date' => $date,
					'continuity_day' => $continuity_day,
					'desc' => $desc,
					'create_time' => time()
				);
				$sign_res = $Model->table('teach_sign_log')->add($data);
				if ($user_coupon_res && $sign_res) {
					$Model->commit();
					api_return(1, '签到成功', $data);
				} else {
					$Model->rollback();
					api_return(2, '签到失败，请稍后重试');
				}
			} else {
				api_return(2, '今日已签到');
			}
		} catch (\Exception $e) {
			api_return(2, '系统繁忙，请稍后再试');
		}
	}

	/**
	 * 学习中心
	 * */
	public function studyCenter()
	{
		$input = I('post.');

		$uid = $input['uid'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('ucenter_member')->field('all_study_time,today_study_time')->where(array('id' => $uid))->find();
		$info['all_study_time'] = studyTimeFormat($info['all_study_time']);
		$info['today_study_time'] = studyTimeFormat($info['today_study_time']);

		$list = M('video_study')->field('vc_id,vt_id')->where(array('uid' => $uid))->group('vc_id')->order('study_time desc')->limit(10)->select();

		if ($list) {
			foreach ($list as &$v) {
				$video_info = M('video_course')->field('id,img,name')->where(array('id' => $v['vc_id']))->find();
				if ($video_info) {
					//查询在线课程是否已经过期
					$expire_time = getDbFieldValue('user_video_course', array('uid' => $uid, 'vc_id' => $v['vc_id']), 'expire_time');
					if ($expire_time == 0) {
						$v['is_expire'] = 0;
					} else {
						$v['is_expire'] = $expire_time < time() ? 1 : 0;
					}

					$tree_count = videoTreeCount($v['vc_id']);

					$v['video_tree_count'] = $tree_count;
					$v['img'] = getPicture($video_info['img']);
					$v['name'] = $video_info['name'];

					$videoCourseStudyInfo = getVideoCourseStudyInfo($v['vc_id']);
					$v['vt_id'] = $videoCourseStudyInfo['vt_id'];
					if ($videoCourseStudyInfo) {
						$section = $videoCourseStudyInfo['section'];
						$v['section'] = $section;
						if ($section == $tree_count) {
							$admin_vc_id = M('video_course')->where(array('id' => $v['vc_id']))->getField('copy_id');
							$last_parent_info = M('video_tree')->field('id')->where(array('vc_id' => $admin_vc_id, 'type' => 1))->order('id desc')->find();
							$last_info = M('video_tree')->field('duration')->where(array('pid' => $last_parent_info['id']))->order('id desc')->find();
							if ($last_info['duration'] <= $videoCourseStudyInfo['duration']) {
								$v['is_over'] = 1;
							} else {
								$v['is_over'] = 0;
							}
						}
					} else {
						$v['section'] = 0;
						$v['is_over'] = 0;
					}
				} else {
					unset($v);
				}
			}
		} else {
			$list = array();
		}

		$data = array(
			'info' => $info,
			'list' => array_merge($list)
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 学习中心-全部课程
	 * */
	public function studyAllVideoCourse()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$type = $input['type'] ? $input['type'] : 1;//1：全部课程，2：过期课程
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$where['uvc.uid'] = $uid;
		if ($type == 2) $where['uvc.expire_time'] = array('between', array(1, time()));

		$list = M('user_video_course uvc')->join('teach_video_course vc ON uvc.vc_id = vc.id')
			->field('vc.id,vc.img,vc.name,uvc.expire_time,vc.copy_id')
			->where($where)
			->page($page, $pagesize)
			->select();

		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);
				if ($v['expire_time'] > time() || $v['expire_time'] == 0) {
					$v['is_expire'] = 0;
				} else {
					$v['is_expire'] = 1;
				}

				$tree_count = videoTreeCount($v['id']);
				$v['tree_count'] = $tree_count;
				$videoCourseStudyInfo = getVideoCourseStudyInfo($v['id']);

				if ($videoCourseStudyInfo) {
					$v['vt_id'] = $videoCourseStudyInfo['vt_id'];
					$section = $videoCourseStudyInfo['section'];
					$v['section'] = $section;
					if ($section == $tree_count) {
						$last_parent_info = M('video_tree')->field('id')->where(array('vc_id' => $v['copy_id'], 'type' => 1))->order('id desc')->find();
						$last_info = M('video_tree')->field('duration')->where(array('pid' => $last_parent_info['id']))->order('id desc')->find();
						if ($last_info['duration'] <= $videoCourseStudyInfo['duration']) {
							$v['is_over'] = 1;
						} else {
							$v['is_over'] = 0;
						}
					}
				} else {
					$parent_list = M('video_tree')->where(array('vc_id' => $v['copy_id'], 'type' => 1))->select();
					$vt_id = 0;
					if ($parent_list) {
						foreach ($parent_list as &$val) {
							$son_list = M('video_tree')->where(array('pid' => $val['id'], 'type' => 2))->select();
							if (count($son_list) > 0) {
								$vt_id = $son_list[0]['id'];
								break;
							}
						}
					}

					$v['vt_id'] = $vt_id;
					$v['section'] = 0;
					$v['is_over'] = 0;
				}
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 我的
	 * */
	public function userCenter()
	{
		$input = I('post.');

		$uid = $input['uid'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = getUserInfo($uid, 'id,avatar,username,id_account,is_edit_pwd,iid');
		if ($info) {
			if ($info['iid']) {
				$mobile = getDbFieldValue('institution', array('id' => $info['iid']), 'mobile');
			} else {
				$mobile = '';
			}
			$info['mobile'] = $mobile;

			//默认密码
			$default_pwd = C('DEFAULT_PWD');
			$info['default_pwd'] = $default_pwd;
			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '获取数据失败');
		}
	}

	/**
	 * 设置密码
	 * */
	public function setPassword()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$old_password = $input['old_password'];
		$new_password = $input['new_password'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($old_password)) api_return(2, '请输入原密码');
		if (empty($new_password)) api_return(2, '请输入新密码');
		if ($old_password == $new_password) api_return(2, '原密码和新密码一致，请重新输入');

		$info = getUserInfo($uid, 'id,password');
		if ($info['password'] != $this->think_ucenter_md5($old_password, '{`47CxmWwv[nV/?)^L1YRz-&0%rjQAtXp53.,#qT')) api_return(2, '原密码错误，请重新输入');
		$data = array(
			'password' => $this->think_ucenter_md5($new_password, '{`47CxmWwv[nV/?)^L1YRz-&0%rjQAtXp53.,#qT'),
			'is_edit_pwd' => 1,
			'update_time' => time(),
		);
		$res = M('ucenter_member')->where(array('id' => $uid))->save($data);
		if ($res) {
			api_return(1, '密码设置成功');
		} else {
			api_return(2, '密码设置失败');
		}
	}

	/**
	 * 我的订单
	 * */
	public function orderCount()
	{
		$input = I('post.');
		$uid = $input['uid'];
		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		//直播课订单
		$live_count = M('order')->where(array('uid' => $uid, 'type' => 1, 'is_del' => 0, 'is_pay' => 1))->count();
		//面授课订单
		$face_count = M('order')->where(array('uid' => $uid, 'type' => 2, 'is_del' => 0, 'is_pay' => 1))->count();
		//在线课订单
		$video_count = M('order')->where(array('uid' => $uid, 'type' => 3, 'is_del' => 0, 'is_pay' => 1))->count();
		//商城订单
		$shop_count = M('order')->where(array('uid' => $uid, 'type' => 4, 'is_del' => 0, 'is_pay' => 1))->count();
		$data = array(
			'live_count' => $live_count,
			'face_count' => $face_count,
			'video_count' => $video_count,
			'shop_count' => $shop_count,
		);
		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 直播课订单列表
	 * */
	public function liveOrderList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$list = M('order o')
			->join('teach_vice_order vo ON o.id = vo.order_id')
			->field('o.id,o.order_sn,vo.img,vo.name,vo.live_open_time,o.all_price,o.pay_time,vo.to_id')
			->where(array('o.uid' => $uid, 'o.type' => 1, 'o.is_pay' => 1, 'o.is_del' => 0))
			->page($page, $pagesize)
			->select();

		if ($list) {
			foreach ($list as &$v) {
				$live_info = M('live_course')->field('audit_status,is_del')->where(array('id' => $v['to_id']))->find();
				$v['img'] = getPicture($v['img']);
				$v['pay_time'] = time_format($v['pay_time'], 'Y-m-d H:i');
				$v['live_open_time'] = time_format($v['live_open_time'], 'Y-m-d H:i');
				$v['live_status'] = $live_info['audit_status'];

				if ($live_info['audit_status'] == 0 || $live_info['audit_status'] == 1) {
					$v['live_status_desc'] = '未开始';
				} else if ($live_info['audit_status'] == 2) {
					$v['live_status_desc'] = '观看直播';
				} else {
					$v['live_status_desc'] = '已结束';
				}

				$v['is_del'] = $live_info['is_del'];
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 面授课订单列表
	 * */
	public function faceOrderList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$status = $input['status'] ? $input['status'] : 0;//0：全部，1：报名中，2：开课中，3：已完结
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$where['o.uid'] = $uid;
		$where['o.type'] = 2;
		$where['o.is_pay'] = 1;
		$where['o.is_del'] = 0;
		if ($status) $where['c.status'] = $status;

		$list = M('face_course c')
			->join('teach_vice_order vc ON vc.to_id = c.id')
			->join('teach_order o ON vc.order_id = o.id')
			->field('o.id,o.order_sn,c.status,vc.to_id,vc.img,vc.name,c.count,o.all_price,o.pay_time,vc.style,o.group_join_id')
			->where($where)
			->page($page, $pagesize)
			->select();

		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);

				if ($v['status'] == 1) {
					$status_desc = '报名中';
				} else if ($v['status'] == 2) {
					$status_desc = '开课中';
				} else if ($v['status'] == 3) {
					$status_desc = '已完结';
				}

				if ($v['style'] == 1 && $v['group_join_id'] > 0) {
					//团购
					$group_join_status = M('group_join')->where(array('id' => $v['group_join_id']))->getField('status');
					if ($group_join_status == 1) {
						$status_desc = '拼团中';
					} else if ($group_join_status == 2) {
						$status_desc = '拼团成功';
					} else if ($group_join_status == 3) {
						$status_desc = '拼团失败';
					}
				}
				$v['status_desc'] = $status_desc;

				$v['pay_time'] = time_format($v['pay_time'], 'Y.m.d H:i');
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 在线课订单列表
	 * */
	public function videoOrderList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$status = $input['status'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$where['uid'] = $uid;
		$where['type'] = 3;
		$where['is_del'] = 0;
		$where['is_pay'] = 1;
		if ($status > 0) $where['video_status'] = $status;

		$list = M('order')->field('id,order_sn,video_status,pay_price,pay_time')->where($where)->order('pay_time desc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$look_auth = 0;
				$vt_id = 0;
				$vice_order_info = M('vice_order')->field('to_id,img,name,price,style')->where(array('order_id' => $v['id']))->find();
				$v['img'] = getPicture($vice_order_info['img']);
				$v['name'] = $vice_order_info['name'];

				$expire_time = getUserVideoCourseExpireTime($uid, $vice_order_info['to_id']);

				$v['expire_time'] = $expire_time ? time_format($expire_time, 'Y.m.d H:i') : '永不过期';
				$v['pay_time'] = time_format($v['pay_time'], 'Y.m.d H:i');

				if ($vice_order_info['style'] > 0 && $vice_order_info['style'] == 1) {
					$v['style_desc'] = '团购价';
				} else if ($vice_order_info['style'] > 0 && $vice_order_info['style'] == 2) {
					$v['style_desc'] = '秒杀价';
				}

				if ($v['video_status'] != 3) {
					if ($expire_time == 0 || $expire_time > time()) {
						$look_auth = 1;
						$new_study_info = M('video_study')->where(array('uid' => $uid, 'vc_id' => $vice_order_info['to_id']))->order('study_time desc')->find();
						if ($new_study_info) {
							$vt_id = $new_study_info['vt_id'];
						} else {
							$video_tree_info = M('video_tree')->where(array('vc_id' => $vice_order_info['to_id']))->order('id asc')->find();
							$vt_id = $video_tree_info['id'];
						}
					}
				}
				$v['style'] = $vice_order_info['style'];

				if ($v['video_status'] == 1) {
					$status_desc = '待评价';
				} else if ($v['video_status'] == 2) {
					$status_desc = '已完成';
				} else if ($v['video_status'] == 3) {
					$status_desc = '已过期';
				}
				$v['status_desc'] = $status_desc ? $status_desc : '';

				$v['look_auth'] = $look_auth;
				$v['vc_id'] = $vice_order_info['to_id'];
				$v['vt_id'] = $vt_id;

				$v['tree_count'] = videoTreeCount($vice_order_info['to_id']);
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 课程评价页面数据回显
	 * */
	public function videoCommentPageData()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];

		if (empty($id)) api_return(2, '订单ID缺失');
		if (empty($uid)) api_return(2, '你还未登录，请先登录');

		$info = M('order')->field('id,pay_time,pay_price')->where(array('id' => $id))->find();
		if ($info) {
			$vice_order_info = M('vice_order')->field('to_id,img,name,style')->where(array('order_id' => $id))->find();

			$info['pay_time'] = time_format($vice_order_info['pay_time'], 'Y.m.d H:i');
			$info['img'] = getPicture($vice_order_info['img']);

			$expire_time = getUserVideoCourseExpireTime($uid, $vice_order_info['to_id']);
			$info['expire_time'] = $expire_time ? time_format($expire_time, 'Y.m.d H:i') : '永不过期';

			$info['tree_count'] = videoTreeCount($vice_order_info['to_id']);
			$info['name'] = $vice_order_info['name'];

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 在线课评价
	 * */
	public function commentVideo()
	{
		$input = I('post.');

		$id = $input['id'];
		$uid = $input['uid'];
		$star = $input['star'];
		$content = $input['content'];

		if (empty($id)) api_return(2, '订单ID缺失');
		if (empty($uid)) api_return(2, '你还未登录，请先登录');

		$info = M('order')->field('pay_time,pay_price')->where(array('id' => $id))->find();
		if ($info) {
			$model = M();
			$model->startTrans();
			try {
				$time = time();

				$order_data = array(
					'video_status' => 2,
					'update_time' => $time
				);
				$order_res = $model->table('teach_order')->where(array('id' => $id))->save($order_data);

				$to_id = $model->table('teach_vice_order')->where(array('order_id' => $id))->getField('to_id');
				$data = array(
					'uid' => $uid,
					'order_id' => $id,
					'to_id' => $to_id,
					'content' => $content,
					'star' => $star,
					'type' => 1,
					'status' => $star > 3 ? 1 : 0,
					'create_time' => $time
				);
				$comment_res = $model->table('teach_comment')->add($data);
				if ($order_res && $comment_res) {
					$model->commit();
					api_return(1, '评价成功');
				} else {
					$model->rollback();
					api_return(2, '评价失败');
				}
			} catch (\Exception $e) {
				api_return(2, '系统繁忙，请稍后再试');
			}
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 商城订单列表
	 * */
	public function shopOrderList()
	{
		$input = I('post.');
		$uid = $input['uid'];
		$status = $input['status'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$where['uid'] = $uid;
		$where['type'] = 4;
		$where['is_del'] = 0;
		$where['is_pay'] = 1;
		if ($status > 0) $where['status'] = $status;

		$list = M('order')->field('id,order_sn,status')->where($where)->order('id desc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$vice_order_list = M('vice_order')->field('img,name,price,spec,count')->where(array('order_id' => $v['id']))->select();
				if ($vice_order_list) {
					foreach ($vice_order_list as &$val) {
						$val['img'] = getPicture($val['img']);
						$val['spec'] = implode('；', json_decode($val['spec'], true));
					}
				}
				$v['goods_list'] = $vice_order_list;
				$v['pay_time'] = time_format($v['pay_time'], 'Y-m-d H:i');
				$v['status_str'] = doOrderStatus($v['status']);
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 商城订单详情
	 * */
	public function shopOrderDetail()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '订单ID缺失');

		$info = M('order')->field('id,order_sn,pay_price,get_username,get_mobile,get_province,get_city,get_area,get_address,pay_time,status')->where(array('id' => $id, 'is_del' => 0))->find();
		if ($info) {
			$info['pay_time'] = time_format($info['pay_time'], 'Y-m-d H:i');
			$info['status_str'] = doOrderStatus($info['status']);

			$vice_order_list = M('vice_order')->field('to_id id,img,name,price,spec,count')->where(array('order_id' => $info['id']))->select();
			if ($vice_order_list) {
				$all_price = 0;
				foreach ($vice_order_list as &$val) {
					$all_price += $val['price'] * $val['count'];

					$val['img'] = getPicture($val['img']);
					$val['spec'] = implode('；', json_decode($val['spec'], true));
				}
			}
			$info['goods_list'] = $vice_order_list;
			$info['all_price'] = $all_price;

			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '订单不存在或已删除');
		}
	}

	/**
	 * 课程收藏列表
	 * */
	public function videoCollectList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$type = $input['type'] ? $input['type'] : 1;//1：整套课程，2：单个课程
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$where['uid'] = $uid;
		$where['type'] = $type;
		$where['is_collect'] = 1;
		$list = M('collect')->field('id,to_id')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as $k => &$v) {
				if ($type == 1) {
					$info = M('video_course')->field('img,name')->where(array('id' => $v['to_id']))->find();
					if ($info) {
						$v['img'] = getPicture($info['img']);
						$v['name'] = $info['name'];
						$v['tree_count'] = videoTreeCount($v['to_id']);
					} else {
						unset($list[$k]);
					}
				} else {
					$info = M('video_tree')->field('name')->where(array('id' => $v['to_id']))->find();
					if ($info) {
						$v['name'] = $info['name'];
					} else {
						unset($list[$k]);
					}
				}
			}

			api_return(1, '获取数据成功', array_merge($list));
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 收货地址列表
	 * */
	public function addressList()
	{
		$input = I('post.');
		$uid = $input['uid'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$list = M('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(array('uid' => $uid))->order('is_default desc,create_time desc')->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['province'] = getProvinceName($v['province_id']);
				$v['city'] = getCityName($v['city_id']);
				$v['area'] = getAreaName($v['area_id']);
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无收货地址');
		}
	}

	/**
	 * 收货地址详情
	 * */
	public function addressDetail()
	{
		$input = I('post.');
		$id = $input['id'];
		if (empty($id)) api_return(2, '收货地址ID缺失');
		$info = M('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(array('id' => $id))->find();
		if ($info) {
			$info['region'] = array(getProvinceName($info['province_id']), getCityName($info['city_id']), getAreaName($info['area_id']));
			$info['defaultIndex'] = $info['is_default'] == 1 ? 0 : 1;
			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '收货地址不存在或已删除');
		}
	}

	/**
	 * 添加收货地址
	 * */
	public function addAddress()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$username = $input['username'];
		$mobile = $input['mobile'];
		$province = $input['province'];
		$city = $input['city'];
		$area = $input['area'];
		$address = $input['address'];
		$is_default = $input['is_default'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($province) || empty($city) || empty($area) || empty($address)) api_return(2, '请完善收货地址');
		if (empty($username)) api_return(2, '请填写收货人姓名');
		if (empty($mobile)) api_return(2, '请填写联系方式');

		if ($is_default == 1) {
			//查询默认的收货地址
			$default_info = M('address')->where(array('uid' => $uid, 'is_default' => 1))->find();
		} else {
			//查询是不是第一个收货地址，是第一个收货地址的话，就设置成默认的
			$count = M('address')->where(array('uid' => $uid))->count();
			if ($count == 0) $is_default = 1;
		}
		$data = array(
			'uid' => $uid,
			'username' => $username,
			'mobile' => $mobile,
			'province_id' => getProvinceId($province),
			'city_id' => getCityId($province, $city),
			'area_id' => getAreaId($province, $city, $area),
			'address' => $address,
			'is_default' => $is_default,
			'create_time' => time()
		);
		$res = M('address')->add($data);
		if ($res) {
			M('address')->where(array('id' => $default_info['id']))->setField('is_default', 0);
			api_return(1, '添加成功');
		} else {
			api_return(2, '添加失败');
		}
	}

	/**
	 * 编辑收货地址
	 * */
	public function editAddress()
	{
		$input = I('post.');

		$id = $input['id'];
		$username = $input['username'];
		$mobile = $input['mobile'];
		$province = $input['province'];
		$city = $input['city'];
		$area = $input['area'];
		$address = $input['address'];
		$is_default = $input['is_default'];

		if (empty($id)) api_return(2, '收货地址ID缺失');
		if (empty($province) || empty($city) || empty($area) || empty($address)) api_return(2, '请完善收货地址');
		if (empty($username)) api_return(2, '请填写收货人姓名');
		if (empty($mobile)) api_return(2, '请填写联系方式');

		//查询默认的收货地址
		$default_info = M('address')->where(array('id' => $id))->find();
		$data = array(
			'username' => $username,
			'mobile' => $mobile,
			'province_id' => getProvinceId($province),
			'city_id' => getCityId($province, $city),
			'area_id' => getAreaId($province, $city, $area),
			'address' => $address,
			'is_default' => $is_default,
			'update_time' => time()
		);
		$res = M('address')->where(array('id' => $id))->save($data);
		if ($res) {
			if ($is_default == 1) {
				if ($default_info['is_default'] != 1) {
					//将原来的默认收货地址修改成非默认
					M('address')->where(array('uid' => $default_info['uid'], 'is_default' => 1, 'id' => array('neq', $id)))->setField('is_default', 0);
				}
			}
			api_return(1, '编辑成功');
		} else {
			api_return(2, '编辑失败');
		}
	}

	/**
	 * 删除收货地址
	 * */
	public function delAddress()
	{
		$input = I('post.');
		$id = $input['id'];
		if (empty($id)) api_return(2, '收货地址ID缺失');
		$info = M('address')->where(array('id' => $id))->find();
		if ($info) {
			$res = M('address')->where(array('id' => $id))->delete();
			if ($res) {
				api_return(1, '删除成功');
			} else {
				api_return(2, '删除失败');
			}
		} else {
			api_return(2, '收货地址不存在或已删除');
		}
	}

	/**
	 * 系统通知列表
	 * */
	public function msgList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$type = $input['type'];//0:未读，1：已读
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if ($type == 1) {
			//已读
			$where = ' (uid = ' . $uid . ' || uid = 0) and FIND_IN_SET(' . $uid . ',read_uid) ';
		} else {
			//未读
			$where = ' (uid = ' . $uid . ' || uid = 0) and NOT FIND_IN_SET(' . $uid . ',read_uid) ';
		}

		$list = M('msg')->field('id,oid,title,content,sys_content,type,create_time')->where($where)->order('id desc')->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['create_time'] = time_format($v['create_time']);
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 消息详情
	 * */
	public function msgDetail()
	{
		$input = I('post.');

		$id = $input['id'];//消息id
		$uid = $input['uid'];//用户id
		$status = $input['status'];//0：未读；1：已读

		if (empty($id)) return api_return(2, '消息ID缺失');

		$info = M('msg')->field('title,create_time,content,sys_content,type')->where(['id' => $id])->find();
		$info['create_time'] = date('Y-m-d H:i', $info['create_time']);
		if ($status == 0) {
			$read_uid = M('msg')->where(['id' => $id])->getField('read_uid');
			if (empty($read_uid)) {
				$read_uid = $uid;
			} else {
				$read_uid = $read_uid . "," . $uid;
			}
			M('msg')->where(['id' => $id])->setField('read_uid', $read_uid);
		}

		if ($info['type'] == 3) $info['content'] = str_replace('<img src="', ' < img style = "width: 100%; height: auto" src = "' . getHost(), $info['sys_content']);

		if ($info) {
			return api_return(1, '获取数据成功', $info);
		} else {
			return api_return(2, '消息不存在');
		}
	}

	/**
	 * 我的卡包
	 * */
	public function userCoupon()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$status = $input['status'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$where['uc.uid'] = $uid;
		if ($status > -1) $where['uc.status'] = $status;
		$list = M('user_coupon uc')
			->join('teach_coupon c ON uc.cid = c.id')
			->field('uc.id,uc.status,uc.expire_time,c.name,c.min_price,c.deduct_price')
			->where($where)
			->page($page, $pagesize)
			->order('uc.status asc,uc.id desc')
			->select();

		if ($list) {
			foreach ($list as &$val) {
				$val['expire_time'] = time_format($val['expire_time'], 'Y-m-d');
				if ($val['expire_time'] < date('Y-m-d') && $val['status'] != 2) {
					$val['status'] = 2;

					//将过期时间已过期且状态非已过期优惠券的状态修改成已过期
					$data = array(
						'status' => 2,
						'update_time' => time()
					);
					M('user_coupon')->where(array('id' => $val['id']))->save($data);
				}
			}
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无更多数据');
		}
	}

	/**
	 * 推广赚钱
	 * */
	public function userProfitList()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		if ($page == 1) {
			//总收益
			$profit = getDbFieldValue('ucenter_member', array('id' => $uid), 'profit');
			//累计推广人数
			$son_count = M('ucenter_member')->where(array('share_uid' => $uid))->count();
		}

		$list = M('user_profit')->where(array('uid' => $uid))->page($page, $pagesize)->select();
		if ($list) {
			foreach ($list as &$v) {
				$username = getDbFieldValue('ucenter_member', array('id' => $v['son_uid']), 'username');
				$v['username'] = $username;

				if ($v['style'] == 1) {
					$v['profit'] = '+' . $v['profit'];
				} else {
					$v['profit'] = '-' . $v['profit'];
				}

				if ($v['type'] == 4) {
					$v['type_desc'] = '商品';
				} else {
					$v['type_desc'] = '课程';
				}

				$v['create_time'] = time_format($v['create_time'], 'Y.m.d');
			}
		} else {
			$list = array();
		}

		$data = array(
			'profit' => $profit,
			'son_count' => $son_count,
			'list' => $list
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 提现页面数据
	 * */
	public function withdrawPageData()
	{
		$input = I('post.');

		$uid = $input['uid'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$profit = getDbFieldValue('ucenter_member', array('id' => $uid), 'profit');
		$min_withdraw = C('MIN_WITHDRAW');

		$data = array(
			'profit' => $profit,
			'min_withdraw' => $min_withdraw
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 资讯列表
	 * */
	public function informationList()
	{
		$input = I('post.');

		$type_id = $input['type_id'];
		$page = $input['page'] ? $input['page'] : 1;
		$pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

		$empty = array(
			array(
				'id' => '0',
				'name' => '全部'
			)
		);
		$type_list = M('information_type')->field('id,name')->select();
		$type_list = array_merge($empty, $type_list);

		if ($type_id) $where['type_id'] = $type_id;
		$list = M('information')->field('id,img,title,content,create_time')->where($where)->page($page, $pagesize)->order('create_time desc')->select();
		if ($list) {
			foreach ($list as &$v) {
				$v['img'] = getPicture($v['img']);
				$v['create_time'] = time_format($v['create_time'], 'Y-m-d');
			}
		} else {
			$list = array();
		}

		$data = array(
			'type_list' => $type_list,
			'list' => $list
		);

		api_return(1, '获取数据成功', $data);
	}

	/**
	 * 资讯详情
	 * */
	public function informationDetail()
	{
		$input = I('post.');

		$id = $input['id'];

		if (empty($id)) api_return(2, '资讯ID缺失');

		$info = M('information')->field('id,title,content,from,create_time')->where(array('id' => $id))->find();
		if ($info) {
			$info['content'] = str_replace('<img src="', ' < img style = "width: 100%; height: auto" src = "' . getHost(), $info['content']);
			$info['create_time'] = time_format($info['create_time'], 'Y-m-d H:i');
			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '资讯不存在或已删除');
		}
	}

	/**
	 * 我要加盟【提交申请】
	 * */
	public function applyInstitution()
	{
		$input = I('post.');
		$uid = $input['uid'];
		$username = $input['username'];
		$mobile = $input['mobile'];
		$IDcard = $input['idcard'];
		$card_front = $input['card_front'];
		$card_behind = $input['card_behind'];
		$hold_card = $input['hold_card'];
//		$business_license = $input['business_license'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($username)) api_return(2, '请输入联系人姓名');
		if (empty($mobile)) api_return(2, '请输入联系方式');
		if (empty($IDcard)) api_return(2, '请输入法人身份证');
		if (empty($card_front)) api_return(2, '请上传身份证正面');
		if (empty($card_behind)) api_return(2, '请上传身份证反面');
		if (empty($hold_card)) api_return(2, '请上传手持身份证');
//		if (empty($business_license)) api_return(2, '请上传营业执照');

		$mobile_count = M('institution')->where(array('mobile' => $mobile))->count();
		if ($mobile_count > 0) api_return(2, '该手机号已被使用');

		$idcard_count = M('institution')->where(array('IDcard' => $IDcard))->count();
		if ($idcard_count > 0) api_return(2, '该身份证号码已被使用');

		$data = array(
			'uid' => $uid,
			'username' => $username,
			'mobile' => $mobile,
			'IDcard' => $IDcard,
			'card_front' => $card_front,
			'card_behind' => $card_behind,
			'hold_card' => $hold_card,
//			'business_license' => $business_license
		);

		$count = M('institution')->where(array('uid' => $uid))->count();
		if ($count > 0) {
			//编辑提交
			$data['update_time'] = time();
			$data['status'] = 0;
			$res = M('institution')->where(array('uid' => $uid))->save($data);
		} else {
			//首次提交
			$data['create_time'] = time();
			$res = M('institution')->add($data);
		}
		if ($res) {
			M('ucenter_member')->where(array('id' => $uid))->setField('mobile', $mobile);

			api_return(1, '提交申请成功');
		} else {
			api_return(2, '提交申请失败');
		}
	}

	/**
	 * 我要加盟【数据回显】
	 * */
	public function institutionInfo()
	{
		$input = I('post.');

		$uid = $input['uid'];
		if (empty($uid)) api_return(2, '您还未登录，请先登录');

		$info = M('institution')->field('id,username,mobile,IDcard,card_front,card_behind,hold_card,status')->where(array('uid' => $uid))->find();
		if ($info) {
			$info['card_front_path'] = getPicture($info['card_front']);
			$info['card_behind_path'] = getPicture($info['card_behind']);
			$info['hold_card_path'] = getPicture($info['hold_card']);
			api_return(1, '获取数据成功', $info);
		} else {
			api_return(2, '暂无加盟申请数据');
		}
	}

	/**
	 * 意见反馈分类数据
	 * */
	public function feedbackType()
	{
		$list = M('feedback_tag')->field('id,name')->select();
		if ($list) {
			api_return(1, '获取数据成功', $list);
		} else {
			api_return(2, '暂无数据');
		}
	}

	/**
	 * 意见反馈
	 * */
	public function addFeedback()
	{
		$input = I('post.');

		$uid = $input['uid'];
		$type_name = $input['type_name'];
		$content = $input['content'];

		if (empty($uid)) api_return(2, '您还未登录，请先登录');
		if (empty($type_name)) api_return(2, '请选择反馈标签');
		if (empty($content)) api_return(2, '请输入反馈内容');

		$data = array(
			'uid' => $uid,
			'type_name' => $type_name,
			'type' => 1,
			'content' => $content,
			'create_time' => time()
		);
		$res = M('feedback')->add($data);
		if ($res) {
			api_return(1, '提交成功');
		} else {
			api_return(2, '提交失败');
		}
	}

	public function pull()
	{
		$roomID = '123456';
		$SDKAppID = intval(C('YUNSDKAPPID'));
		$secret = C('YUNSECRET');
		$userID = 'Dave_pull_xcx';
		$userSig = getUserSig($userID);
		$data = array(
			'room_id' => $roomID,
			'sdk_appid' => $SDKAppID,
			'secret' => $secret,
			'user_id' => $userID,
			'userSig' => $userSig
		);
		api_return(1, '获取数据成功', $data);
	}

	public function getUserSig()
	{
		$input = I('post.');
		$userID = $input['userID'];
		$userSig = getUserSig($userID);
		api_return(1, '获取数据成功', $userSig);
	}
}